Python:结构包sam的数据格式几乎是不同的

2024-06-02 08:54:14 发布

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

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


Tags: importdatalenstructpackprint区别chr
1条回答
网友
1楼 · 发布于 2024-06-02 08:54:14

这种效果是因为对齐和实现它所需的填充。如果您参考Python标准库文档Struct,它在第7.3.2.1节(我指的是python2.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。在

相关问题 更多 >