Struct. Error: Unpack Requires a Buffer of 4 Bytes

Struct. Error: Unpack Requires a Buffer of 4 Bytes

I want to convert data from a device from bites to float I use the code from this answer

bytes to float

import struct

byte_file = b'+001.80\r'
print(type(byte_file))

y = struct.unpack('f' , byte_file)
print(y)

I get this struct.error: unpack requires a buffer of 4 bytes

The correct outcome should be 1.80 do I need to implement a buffer argument ?

1 Answer

struct is used for binary packed data - data that is not human-readable. b'+001.80\r' is 8 bytes long: b'+', b'0', b'0', b'1', b'.', ....

You can just decode it and use float:

>>> b'+001.80\r'.decode()
'+001.80\r'
>>> float(_)
1.8
>>> import struct
>>> struct.pack('f', _)
b'ff\xe6?'  # doesn't look anything like your data!

However, because your data is 8 bytes long, you could treat it as a single double-precision floating-point value:

>>> struct.unpack('d', b'+001.80\r')
(3.711588247816385e-245,)

But that treats the data as binary-packed: +001.80\r, also known as 2b 30 30 31 2e 38 30 0d, is what 3.711588247816385e-245 looks like in memory.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.