简体   繁体   English

python struct unpack length错误

[英]python struct unpack length error

I've a bytes object with length 41. I tried to unpack it with: 我有一个长度为41的字节对象。我尝试用以下方法打开它的包装:

struct.unpack('2B2B32sBi',data)

But I got a error that: 但是我得到一个错误:

struct.error: unpack requires a bytes object of length 44 struct.error:解压缩需要一个长度为44的字节对象

I think the length of 2B2B32sBi should be 2*1+2*1+32*1+1+4=41 after check the python document. 我认为2B2B32sBi的长度应在检查python文档后为2*1+2*1+32*1+1+4=41 Why am I wrong? 我为什么错了?

See the parts of the documentation regarding alignment: 请参阅文档中有关对齐的部分:

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). 默认情况下,C类型以机器的本机格式和字节顺序表示,并在必要时通过跳过填充字节来正确对齐(根据C编译器使用的规则)。

Native size and alignment are determined using the C compiler's sizeof expression. 使用C编译器的sizeof表达式确定本机大小和对齐方式。 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. 注意'@'和'='之间的区别:两者都使用本机字节顺序,但是后者的大小和对齐方式是标准化的。

To illustrate this: 为了说明这一点:

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

You just encountered padding since you've got bytes data first, and then integer (which has stronger alignment constraints) 您刚遇到填充是因为先获取字节数据,然后获取整数(具有更强的对齐约束)

From the documentation : 文档中

Padding is only automatically added between successive structure members. 仅在连续的结构成员之间自动添加填充。 No padding is added at the beginning or the end of the encoded struct. 在编码结构的开头或结尾不添加填充。

So you have to specify an endianness to disable padding: 因此,您必须指定字节序以禁用填充:

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

Edited for completeness , after reading Galen's excellent answer: just specifying = is better if you don't want to force endianness. 阅读了Galen的出色答案后, 为了完整起见,对其进行了编辑 :如果不想强制字节序,仅指定=会更好。

You may want to read the first note in the struct documentation again. 您可能需要再次阅读struct文档中的第一条注释。 Default is C-aligned data boundaries, so some padding bytes are responsible for the difference. 默认值是C对齐的数据边界,因此一些填充字节是造成差异的原因。 So adding the appropriate byte order should fix the problem. 因此,添加适当的字节顺序应该可以解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM