Convert Bytes to Floating Point Numbers?

Posted on

Question :

Convert Bytes to Floating Point Numbers?

I have a binary file that I have to parse and I’m using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?

Asked By: Cristian

||

Answer #1:

>>> import struct
>>> struct.pack('f', 3.141592654)
b'xdbx0fI@'
>>> struct.unpack('f', b'xdbx0fI@')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'x00x00x80?x00x00x00@x00x00@@x00x00x80@'
Answered By: tzot

Answer #2:

Just a little addition, if you want a float number as output from the unpack method instead of a tuple just write

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

If you have more floats then just write

>>> [x,y] = struct.unpack('ff', b'xdbx0fI@x0bx01I4')
>>> x
3.1415927410125732
>>> y
1.8719963179592014e-07
>>> 
Answered By: NDM

Leave a Reply

Your email address will not be published. Required fields are marked *