Explain the extra padding in struct.pack with native byte order

后端 未结 1 333
囚心锁ツ
囚心锁ツ 2021-01-21 00:03

Can someone explain why I get extra bytes when I use native Byte order with struct.pack?

>>> import struct
>>> struct.pack(\'cI\', \'a\', 1)
\'         


        
相关标签:
1条回答
  • 2021-01-21 00:58

    This is explain in the struct module documentation:

    Note: By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

    In the Byte Order, Size, Alignment:

    ....

    Native size and alignment are determined using the C compiler's sizeof expression. This is always combined with native byte order.

    ...

    Notes:

    1. Padding is only automatically added between successive structure members.
    2. 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 ‘!’.
    3. 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.
    0 讨论(0)
提交回复
热议问题