python结构解包长度

2024-04-19 13:20:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字节对象,长度为41。我试着用:

struct.unpack('2B2B32sBi',data)

但我有个错误:

struct.error: unpack requires a bytes object of length 44

我认为在检查python文档之后,2B2B32sBi的长度应该是2*1+2*1+32*1+1+4=41。为什么我错了?在


Tags: of对象文档data字节bytesobject错误
3条回答

您可能需要再次阅读struct documentation中的第一个注释。 默认值是C对齐的数据边界,因此一些填充字节负责造成这种差异。因此,添加适当的字节顺序应该可以解决这个问题。在

请参见documentation中有关对齐的部分:

By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).

Native size and alignment are determined using the C compiler’s sizeof expression. This is always combined with native byte order.

Note the difference between '@' and '=': both use native byte order, but the size and alignment of the latter is standardized.

为了说明这一点:

>>> import struct
>>> struct.calcsize("2B2B32sBi")
44
>>> struct.calcsize("@2B2B32sBi")
44
>>> struct.calcsize("=2B2B32sBi")
41

您刚刚遇到了padding,因为首先是字节数据,然后是整数(具有更强的对齐约束)

documentation

Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct.

因此,需要指定一个endianness来禁用填充:

struct.unpack('<2B2B32sBi',data)

为了完整性进行了编辑,在阅读了Galen的优秀答案之后:如果您不想强制endianness,只指定=会更好。在

相关问题 更多 >