有人可以解释为什么我在使用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'
所以本机字节顺序在它之前有’a’然后是3-(00字节).为什么本地字节顺序具有这些字节而小字节序或大端字节顺序不具有?
最佳答案 这在
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.
….
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.