问题
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:
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.
来源:https://stackoverflow.com/questions/60376438/struct-error-unpack-requires-a-buffer-of-4-bytes