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