struct size confusion:
Michael Yanowitz
m.yanowitz at kearfott.com
Wed Mar 22 10:26:04 EST 2006
Thanks for your and everyone else's feedback.
I got it to work now by prefixing the PACK_FORMAT with "!".
I previously thought I could only use the "!' with the unpack.
I still don't fully understand the byte allignment stuff (I am
sure I will get it eventually), but I am content that it is
working now.
-----Original Message-----
From: python-list-bounces+m.yanowitz=kearfott.com at python.org
[mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf
Of Fredrik Lundh
Sent: Wednesday, March 22, 2006 9:28 AM
To: python-list at python.org
Subject: Re: struct size confusion:
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:
http://docs.python.org/lib/module-struct.html
default is native byte order, native padding:
>>> struct.calcsize("IH")
6
>>> struct.calcsize("HI")
8
to specify other byte orders, use a prefix character. this also disables
padding. e.g.
>>> struct.calcsize("!IH")
6
>>> struct.calcsize("!HI")
6
</F>
--
http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list