Search code examples
pythonstructpack

Python struct.pack()/calcsize()


I want to pack a byte followed by a long. My buffer can only contain 9 elements. Why can't I pack them into the buffer?

>>> from struct import *
>>> calcsize('qB')
9
>>> calcsize('Bq')
12

It returns differently. Why is this?

I'm using Python 2.7.3 by the way.


Solution

  • In your second example, struct.calcsize assumes 3 bytes of padding after the byte so that the long long can begin on a 4-byte boundary.

    If you specify no padding, you'll see they are equivalent:

    >>> calcsize ('Bq')
    12
    >>> calcsize('=Bq')
    9