Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

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

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

so the native Byte order has 'a' and then 3-(00 bytes) before it. Why does the native Byte order have these bytes while little endian or big endian byte order do not?

like image 309
Ben Fogel Avatar asked Jun 22 '26 23:06

Ben Fogel


1 Answers

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.
like image 58
falsetru Avatar answered Jun 24 '26 11:06

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!