python-3.x - struct.error : unpack requires a buffer of 4 bytes

标签 python-3.x struct

我想将设备中的数据从叮咬转换为 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/

相关文章:

c - c 中的 malloc,结构

c - 错误: derefrencing pointer to incomplete type

c++ - 为什么 PyObject_Print 崩溃?

Python "while"循环没有结束

Python 3——[s for s in subsets(S)] and yield

c - 显示名称存储在结构体 C 中

c - C 中结构体的大小

关于 C 中位域排序语义的澄清

python - 紧随其后提取子字符串 - 在 Python 中

python - 如何在 Python f 字符串中跳过十进制的尾随零?