struct.error: unpack 需要 4 个字节的缓冲区 [英] struct.error: unpack requires a buffer of 4 bytes

查看:257
本文介绍了struct.error: unpack 需要 4 个字节的缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将设备中的数据从叮咬转换为浮动我使用这个答案中的代码

要浮动的字节

导入结构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:

<预><代码>>>>b'+001.80\r'.decode()'+001.80\r'>>>漂浮(_)1.8>>>导入结构>>>struct.pack('f', _)b'ff\xe6?'# 看起来不像你的数据!

但是,因为您的数据有 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 看起来像在内存中.

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 ?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆