Bug in struct.pack?

Raymond Hettinger python at rcn.com
Wed Jan 11 12:20:34 CET 2006


[Alex Stapleton]
> from struct import pack
>  >>> pack("B", 1)
> '\x01'
>  >>> pack("BB", 0, 1)
> '\x00\x01'
>  >>> pack("BI", 0, 1)
> '\x00\x00\x00\x00\x01\x00\x00\x00'
>  >>> calcsize("BI")
> 8
>  >>> calcsize("BB")
> 2
>
> Why does an unsigned char suddenly become 4 bytes long when you
> include an unsigned int in the format string? It's consistent
> behaviour but it's incorrect.

You're seeing native alignment come into play.
Specify a standard alignment to avoid padding.

>>> pack("BI", 0, 1)
'\x00\x00\x00\x00\x01\x00\x00\x00'
>>> pack("=BI", 0, 1)
'\x00\x01\x00\x00\x00'

All is explained in the docs:
 http://docs.python.org/lib/module-struct.html


Raymond




More information about the Python-list mailing list