Python struct.Struct.size 返回意外值

标签 python struct

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

问题

代码

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

结果

28

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

解决方法

存在一种解决方法,即将 B 分离到一个单独的 struct 中,如下所示:

代码

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

结果

25

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

最佳答案

来自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 而其余的是 4 所以它将被填充以使其成为 4 因此答案是 28 考虑这个例子

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

这里 B1 并填充 3 并且 f4所以最后它达到了 8,这是预期的。

如前所述here要覆盖它,您将不得不使用非本地方法

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

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

关于Python struct.Struct.size 返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393622/

相关文章:

python - random.choice 在 Python 2 和 3 上给出不同的结果

python - 从 Django 中的一种形式创建对象的多个实例

python - 获取字典中最长的元素

python - 一次重复多个维度的 NumPy 数组?

C:通过指针设置结构的数组成员

c++ - 作为参数传递给函数(c++)时如何修改全局结构?

python - 在 QtableWidget 中显示来自数据库的数据

inheritance - 如何将 'child' 结构传递给接受 'parent' 结构的函数?

c++ - C++ 中的动态结构

c - 段错误 11 从结构打印字符串