Convert Bytes to Floating Point Numbers?

PythonFloating Point

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

>>> 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@'
                      

Solution 2 - Python

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'\xdb\x0fI@')
>>> x
3.1415927410125732

If you have more floats then just write

>>> [x,y] = struct.unpack('ff', b'\xdb\x0fI@\x0b\x01I4')
>>> x
3.1415927410125732
>>> y
1.8719963179592014e-07
>>> 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCristianView Question on Stackoverflow
Solution 1 - PythontzotView Answer on Stackoverflow
Solution 2 - PythonNDMView Answer on Stackoverflow