Question

J'ai un fichier binaire que je dois analyser et j'utilise Python.Existe-t-il un moyen de prendre 4 octets et de les convertir en un nombre à virgule flottante simple précision ?

Était-ce utile?

La solution

>>> import struct
>>> struct.pack('f', 3.141592654)
b'\xdb\x0fI@'
>>> struct.unpack('f', b'\xdb\x0fI@')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'

Autres conseils

Juste un petit ajout, si vous voulez un nombre flottant en sortie de la méthode de décompression au lieu d'un tuple, écrivez simplement

>>> [x] = struct.unpack('f', b'\xdb\x0fI@')
>>> x
3.1415927410125732

Si vous avez plus de flottants, écrivez simplement

>>> [x,y] = struct.unpack('ff', b'\xdb\x0fI@\x0b\x01I4')
>>> x
3.1415927410125732
>>> y
1.8719963179592014e-07
>>> 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top