struct.error: unpack 需要 4 个字节的缓冲区 [英] struct.error: unpack requires a buffer of 4 bytes
问题描述
我想将设备中的数据从叮咬转换为浮动我使用这个答案中的代码
导入结构byte_file = b'+001.80\r'打印(类型(字节文件))y = struct.unpack('f', byte_file)打印(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
:
但是,因为您的数据有 8 个字节长,您可以将其视为单个 double
精度浮点值:
但将数据视为二进制打包:+001.80\r
,也称为 2b 30 30 31 2e 38 30 0d
,就是 3.711588247816385e-245
看起来像在内存中.
I want to convert data from a device from bites to float I use the code from this answer
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 ?
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.
这篇关于struct.error: unpack 需要 4 个字节的缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!