struct size confusion:

Michael Yanowitz m.yanowitz at kearfott.com
Wed Mar 22 08:59:50 EST 2006


Hello:

   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?

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

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

   I will be reading shorts and longs sent from C into Python
through a socket.

   Suppose I know I am getting 34 bytes, and the last 6 bytes are a 2-byte
word followed by a 4-byte int, how can I be assured that it will be in that
format?

   In a test, I am sending data in this format:
  PACK_FORMAT = "HBBBBHBBBBBBBBBBBBBBBBBBBBHI"
which is 34 bytes
   However, when I receive the data, I am using the format:
UNPACK_FORMAT = "!HBBBBHBBBBBBBBBBBBBBBBBBBBHHI"
  which has the extra H in the second to last position to make them
compatible, but that makes it 36 bytes. I am trying to come up with
some explanation as to where the extra 2 bytes come from.

Thanks in advance:




More information about the Python-list mailing list