Convert Bytes to Floating Point Numbers?

Question:

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

||

Answers:

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

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

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

If you have more floats then just write

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

I would add a comment but I don’t have enough reputation.

Just to add some info. If you have a byte buffer containing X amount of floats, the syntax for unpacking would be:

struct.unpack('Xf', ...)

If the values are doubles the unpacking would be:

struct.unpack('Xd', ...)
Answered By: Chance Cuddeback

Comment: let’s say you are receiving a float variable via MODBUS communication protocol (2 registers, 1 int each), you can convert the message with:

floatvar = struct.unpack(‘f’,int1.to_bytes(2,’big’)+int2.to_bytes(2,’big’)).

*note MODBUS is big Endian

Answered By: Rousseau
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.