我在 python 中运行此代码:
import struct
res = struct.pack('hhl', 1, 2, 3)
print(res)
我得到以下输出:
b'\x01\x00\x02\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00'
但我不明白为什么这是输出?毕竟,格式 h
表示 2 个字节,而格式 l
表示 4 个字节。那么为什么在这种情况下我会得到这个输出呢?
最佳答案
来自 struct doc
,
To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment
默认h
可能会被填充,具体取决于您运行的平台。选择“big-endian”( >
)、“little-endian”( <
)或备用 native 样式( =
)以删除填充。例如,
>>> struct.Struct('hhl').size
16
>>> struct.Struct('<hhl').size
8
>>> struct.Struct('>hhl').size
8
>>> struct.Struct('=hhl').size
8
您可以根据您想要匹配的模式来选择一个。如果它是 native 编译应用程序的 C 结构,则它取决于 native 内存布局(例如 16 位架构)以及编译器是否打包或填充。如果是网络协议(protocol),大端或小端,取决于其规范。
关于python - 为什么在尝试打印这个打包结构时会得到这个输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74145197/