Python3.7.0 struct calcsize,bug还是feature?

2024-09-24 20:31:55 发布

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

我试图从字节中解压一个值列表。我想把它们一起读和拆开,但我遇到了这个东西。。。你知道吗

当我们计算串联字符串fmt的大小时,我们得到一个结果, 如果我们计算字符串fmt的所有部分的大小并求和,我们会得到另一个结果(预期结果)。你知道吗

from struct import calcsize

f0 = '3B'
f1 = '2H'
f2 = '1B'
f3 = '4H'
f4 = '2B'

print(calcsize(f0) + calcsize(f1) + calcsize(f2) + calcsize(f3) + calcsize(f4))
# 18       (expected) 

print(calcsize(f0 + f1 + f2 + f3 + f4))
# 20       (what?!! o_O)

可能是我不明白什么?你知道吗


Tags: 字符串fromimport列表字节structf2f1
1条回答
网友
1楼 · 发布于 2024-09-24 20:31:55

以“本机”字节顺序(默认值),struct模块对其结构应用与C相同的填充规则。所以一个填充字节出现在3B2H之间(因为H是两个字节对齐的),另一个填充字节出现在1B4H之间。你知道吗

根据the docs

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.

因此,只要使用非默认的大小/对齐来“修复”这个问题(如果合适的话)。你知道吗

相关问题 更多 >