struct.pack 比它的零件长?
struct.pack longer than its parts?
我想解压 6 个值:2 * UInt16
、1 * UInt32
、1 * UInt16
、2 * Int64
加上字节大小,我得到 26。
但是python好像觉得应该是32:
>>> a = struct.pack("H",0)
>>> len(a)
2 <-- correct
>>> a = struct.pack("L",0)
>>> len(a)
4 <-- correct
>>> a = struct.pack("q",0)
>>> len(a)
8 <-- correct
>>> a = struct.pack("HHLHqq",0,0,0,0,0,0)
>>> len(a)
32 < -- should be 2 + 2 + 4 + 2 + 8 + 8 = 26
>>> a = struct.pack("HHLHq",0,0,0,0,0)
>>> len(a)
24 < -- should be 2 + 2 + 4 + 2 + 8 = 18
>>> a = struct.pack("HHLH",0,0,0,0)
>>> len(a)
10 <-- correct again
struct.unpack
也有同样的问题,解包需要32字节"HHLHqq"。但是,在我的应用程序中,数据是从外部源发送的,只有 26 个字节。
作为解决方法,我可以一个一个地解压它,但肯定有办法禁用此填充?
根据:https://docs.python.org/2/library/struct.html
No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’.
因此您只需指定字节顺序,填充就会消失:
>>> import struct
>>> len(struct.pack("HHLHqq",0,0,0,0,0,0))
40
>>> len(struct.pack("<HHLHqq",0,0,0,0,0,0))
26
>>>
我想解压 6 个值:2 * UInt16
、1 * UInt32
、1 * UInt16
、2 * Int64
加上字节大小,我得到 26。
但是python好像觉得应该是32:
>>> a = struct.pack("H",0)
>>> len(a)
2 <-- correct
>>> a = struct.pack("L",0)
>>> len(a)
4 <-- correct
>>> a = struct.pack("q",0)
>>> len(a)
8 <-- correct
>>> a = struct.pack("HHLHqq",0,0,0,0,0,0)
>>> len(a)
32 < -- should be 2 + 2 + 4 + 2 + 8 + 8 = 26
>>> a = struct.pack("HHLHq",0,0,0,0,0)
>>> len(a)
24 < -- should be 2 + 2 + 4 + 2 + 8 = 18
>>> a = struct.pack("HHLH",0,0,0,0)
>>> len(a)
10 <-- correct again
struct.unpack
也有同样的问题,解包需要32字节"HHLHqq"。但是,在我的应用程序中,数据是从外部源发送的,只有 26 个字节。
作为解决方法,我可以一个一个地解压它,但肯定有办法禁用此填充?
根据:https://docs.python.org/2/library/struct.html
No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’.
因此您只需指定字节顺序,填充就会消失:
>>> import struct
>>> len(struct.pack("HHLHqq",0,0,0,0,0,0))
40
>>> len(struct.pack("<HHLHqq",0,0,0,0,0,0))
26
>>>