我想将设备中的数据从叮咬转换为 float
我使用这个答案中的代码
bytes to float
import struct
byte_file = b'+001.80\r'
print(type(byte_file))
y = struct.unpack('f' , byte_file)
print(y)
我明白了 struct.error: unpack requires a buffer of 4 bytes
正确的结果应该是 1.80
我需要实现一个缓冲区参数吗?
最佳答案
struct
用于二进制打包数据 - 非人类可读的数据。 b'+001.80\r'
8 字节长:b'+', b'0', b'0', b'1', b'.', ...
.
您只需decode
它并使用 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!
但是,由于您的数据有 8 个字节长,您可以将其视为单个
double
-精度浮点值:>>> struct.unpack('d', b'+001.80\r')
(3.711588247816385e-245,)
但这会将数据视为二进制打包:
+001.80\r
,也称为 2b 30 30 31 2e 38 30 0d
,是什么3.711588247816385e-245
内存中的样子。
关于python-3.x - struct.error : unpack requires a buffer of 4 bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60376438/