struct calcsize discrepency?

Duncan Booth duncan.booth at invalid.invalid
Sun Dec 4 09:38:06 EST 2011


Glen Rice <glen.rice.noaa at gmail.com> 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?
> 
When you mix different types in a struct there can be padding inserted 
between the items. In this case the 8 byte unsigned long long must always 
start on an 8 byte boundary so 4 padding bytes are inserted.

See http://docs.python.org/library/struct.html?highlight=struct#byte-order-
size-and-alignment in particular the first sentence:

"By default, C types are represented in the machine’s native format and 
byte order, and properly aligned by skipping pad bytes if necessary 
(according to the rules used by the C compiler)."

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list