struct calcsize discrepency?

Chris Angelico rosuav at gmail.com
Sun Dec 4 09:35:28 EST 2011


On Mon, Dec 5, 2011 at 1:25 AM, 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?

Same thing happens in CPython, and it looks to be the result of alignment.

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

The eight-byte integer is aligned on an eight-byte boundary, so when
it follows a four-byte string, you get four padding bytes inserted.
Put them in the other order, and the padding disappears.

(Caveat: I don't use the struct module much, this is based on conjecture.)

ChrisA



More information about the Python-list mailing list