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?
>>> 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@'
-
7
-
I agree with @dplass, what about other floats. And, why is there a comma at the end of this string? – Startec Aug 26 '14 at 8:57
-
6@startec The question was about 4-byte floats. Which string ends with a comma? Only the tuple from
struct.unpack
has a comma. – tzot Sep 10 '14 at 21:17 -
1@PetrKrampl accuracy of C
float
(single, 4 bytes) and Cdouble
(double, 8 bytes). Pythonfloat
is really Cdouble
. Whatever the accuracy of storing3.141592654
as a Cdouble
, it's lost when it's converted to a Cfloat
(by struct.pack) and then back to Cdouble
(Python extracts the 4-bytes as a Cfloat
and then converts the result back to a Cdouble
/Pythonfloat
). This applies to all implementations of Python that use IEEE754 floating point numbers (CPython does; anyway, I don't know of any non-IEEE754-conformant Python implementation on any system). – tzot Oct 28 '15 at 17:36 -
3Note: to view the individual bytes of the bytearray (indicated by b'), use
list()
. Ex:list(struct.pack('f', 3.141592654))
returns a list of the individual bytes as[219, 15, 73, 64]
. This is very handy. – Gabriel Staples Aug 19 '16 at 3:01
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
>>>