struct size confusion:

Fredrik Lundh fredrik at
Wed Mar 22 09:27:53 EST 2006

Michael Yanowitz wrote:

>    I am relatively new to Python and this is my first post on
> this mailing list.
>    I am confused as to why I am getting size differences in the following
> cases:
> >>> print struct.calcsize("I")
> 4
> >>> print struct.calcsize("H")
> 2
> >>> print struct.calcsize("HI")
> 8
> >>> print struct.calcsize("IH")
> 6
>    Why is it 8 bytes in the third case and why would it be only 6 bytes
> in the last case if it is 8 in the previous?

because modern platforms tend to use an alignment equal to the size of
the item; 2-byte objects are stored at even addresses, 4-byte objects
are stored at addresses that are multiples of four, etc.

in other words, HI is stored as 2 bytes H data plus 2 bytes padding plus
four bytes I data, while IH is four bytes I data, no padding, and 2 bytes
H data.

>    I tried specifying big endian and little endian and they both have
> the same results.

are you sure?  (see below)

>     I suspect, there is some kind of padding involved, but it does not
> seem to be done consistently or in a recognizable method.

the alignment options are described in the library reference:

default is native byte order, native padding:

>>> struct.calcsize("IH")
>>> struct.calcsize("HI")

to specify other byte orders, use a prefix character. this also disables
padding. e.g.

>>> struct.calcsize("!IH")
>>> struct.calcsize("!HI")


More information about the Python-list mailing list