struct calcsize discrepency?

Peter Otten __peter__ at web.de
Sun Dec 4 09:49:36 EST 2011


Glen Rice wrote:

> In IPython:
>>import struct
>>struct.calcsize('4s')
> 4
>>struct.calcsize('Q')
> 8
>>struct.calcsize('4sQ')
> 16
> 
> This doesn't make sense to me.  Can anyone explain?

A C compiler can insert padding bytes into a struct:

"""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.
"""
 
http://docs.python.org/library/struct.html#struct-alignment

You can avoid this by specifying a non-native byte order (little endian, big 
endian, or "network"):

>>> struct.calcsize("4sQ")
16
>>> struct.calcsize("!4sQ")
12





More information about the Python-list mailing list