Can someone explain why I get extra bytes when I use native Byte order with struct.pack?
>>> import struct
>>> struct.pack(\'cI\', \'a\', 1)
\'
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:
- 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.