struct calcsize discrepency?

Dave Angel d at davea.name
Sun Dec 4 09:51:41 EST 2011


On 12/04/2011 09:35 AM, Chris Angelico wrote:
> 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.
>
NOT disappears.  In C, the padding to the largest alignment occurs at 
the end of a structure as well as between items.  Otherwise, an array of 
the struct would not be safely aligned.  if you have an 8byte item 
followed by a 4 byte item, the total size is 16.
> (Caveat: I don't use the struct module much, this is based on conjecture.)
>
> ChrisA


-- 

DaveA




More information about the Python-list mailing list