我试图从字节中解压一个值列表。我想把它们一起读和拆开,但我遇到了这个东西。。。你知道吗
当我们计算串联字符串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)
可能是我不明白什么?你知道吗
以“本机”字节顺序(默认值),
struct
模块对其结构应用与C相同的填充规则。所以一个填充字节出现在3B
和2H
之间(因为H
是两个字节对齐的),另一个填充字节出现在1B
和4H
之间。你知道吗根据the docs:
因此,只要使用非默认的大小/对齐来“修复”这个问题(如果合适的话)。你知道吗
相关问题 更多 >
编程相关推荐