Python结构.结构.尺寸返回意外值

2024-09-30 20:21:47 发布

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

我使用Python将一些文件转换为二进制格式,但遇到了一个奇怪的陷阱。在

问题

代码

import struct
s = struct.Struct('Bffffff')
print s.size

结果

^{pr2}$

显然,预期的大小是25,但它似乎将第一个字节(B)解释为某种4字节的整数。它还将写出一个4字节的整数而不是一个字节。在

解决办法

有一种解决方法,即将B分离成一个单独的struct,如下所示:

代码

import struct
s1 = struct.Struct('B')
s2 = struct.Struct('ffffff')
print s1.size + s2.size

结果

25

这种行为有什么解释吗?在


Tags: 文件代码importsize字节格式二进制整数
2条回答

除非为字节顺序、对齐方式指定任何字符,struct请使用本机字节顺序对齐(@);这会导致填充。在

通过显式指定字节顺序,可以获得所需的内容:

>>> struct.Struct('!Bffffff').size  # network byte order
25
>>> struct.Struct('=Bffffff').size  # native byte order, no alignment.
25
>>> struct.Struct('>Bffffff').size  # big endian
25
>>> struct.Struct('<Bffffff').size  # little endian
25
>>> struct.Struct('@Bffffff').size  # native byte order, alignment. (+ native size)
28

docs

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

如果你测试

>>> import struct
>>> s1 = struct.Struct('B')
>>> print s1.size
1
>>> s1 = struct.Struct('f')
>>> print s1.size
4

所以当你添加它是25。。。但另一方面,B是1,其余的是{},所以它将被填充成{},因此答案是{} 考虑这个例子

^{pr2}$

这里的B1,加了3,而{}是{},所以最后得到了{},这与预期一致。在

如前所述,here要重写它,必须使用非本机方法

>>> s1 = struct.Struct('!Bf')
>>> print s1.size
5

No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’.

相关问题 更多 >