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

Can someone explain why I am getting extra bytes when I use native byte ordering with struct.pack?

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

>>> struct.pack('<cI', 'a', 1)


so the native byte order has 'a' and then 3- (00 bytes) before it. Why does every byte order have bytes, while the byte order in bytes is not limited?


source to share

1 answer

This is explained in the documentation struct


Note: By default, the boxing result of a given C-structure includes bytes with bytes to maintain correct alignment for the C types involved. Similarly, alignment is taken into account when unboxing. This behavior is chosen so that the packed structure's bytes match exactly the in-memory layout of the corresponding C structure. To handle platform-independent data formats, or to omit implicit element bytes, use standard size and alignment instead of native size and alignment: see section " Order, size and alignment of bytes ".

In Order, Size, Byte Alignment :


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



  • Padding is only automatically added between sequential structure members.
  • No additive is added at the beginning or at the end of the coded structure. No additive is added when using non-native size and alignment, for example. with '<,'>, '=, and' !.
  • To align the end of a structure to an alignment requirement of a particular type, end the format with a code for that type with zero recounts. See Examples.


All Articles