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)
>>> struct.unpack('f', b'xdbx0fI@')
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
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

If you have more floats then just write

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

Leave a Reply

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