Python:Struct.pack(format, [...]),虽然格式几乎相同,但打包数据的大小不同

2024-02-29

import struct
data = struct.pack('ici', 1, chr(1), 1)
print(len(data))
#12

data = struct.pack('iic', 1, 1, chr(1))
print(len(data))
#9

两个“data”变量之间似乎没有区别,为什么“len(data)”的结果不同,一个是12,另一个是9


这种效果是由于对齐和实现它所需的填充造成的。如果您参考 Struct 的 Python 标准库文档,它在第 7.3.2.1 节中说(我指的是 Python 2.7 文档):

Notes:
    Padding is only automatically added between successive structure members. No padding is added at the beginning or the end of the encoded struct. 
    No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’. 
    To align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero. See Examples. 

“i”的标准大小是 4 个字节,“c”的标准大小是 1。

在第一个“ici”包中,“c”必须填充为 32 位对齐(即添加三个字节)才能添加最后的“i” - 因此总长度为 12。

在“iic”包中,最后的“c”不必填充,因此长度为9。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python:Struct.pack(format, [...]),虽然格式几乎相同,但打包数据的大小不同 的相关文章

随机推荐