python - 结构中的奇怪格式长度

标签 python struct

我正在尝试解压一张 jpeg 图像,我偶然发现了一个非常有趣的行为。

H格式看起来有3个字节长。我已成功隔离此格式字符串:

print(calcsize('15s2s')) #prints 17
print(calcsize('15sH')) #prints 18

文档说 H 将 2 个字节解压缩为一个整数。

奇怪的是,当我将其更改为这个时,它们都返回 16:

print(calcsize('14s2s')) #prints 16
print(calcsize('14sH')) #prints 16

这是一个错误,还是我遗漏了什么?

最佳答案

请参阅 struct 模块文档的顶部:

Note: By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

强调我的。您将在此处看到对齐填充的效果。

设置字节顺序或使用 = 生成非填充格式:

>>> from struct import calcsize
>>> calcsize('15sH')
18
>>> calcsize('=15sH')
17

关于python - 结构中的奇怪格式长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20593286/

相关文章:

python - 仅将非 None 的参数传递给 Flask 的 url_for

c - 哪种使用 C 数组的数据组织可以生成最快的代码,为什么?

python - 我怎样才能改变矩形的大小

c - 尝试查找一行中单词的索引(以单词数衡量)

c - 在结构上使用 strncpy

c# - struct 有默认构造函数吗?

c# - 我应该如何使用 P/Invoke 将字符串数组传递给 C 库?

javascript - 通过 Python 将 SQL 查询返回到 JavaScript?

python - While循环不断循环Python 3.3

python - 查找替代关键字之一的索引