我正在尝试解压一张 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/