struct curiosity

Mark Dickinson dickinsm at gmail.com
Fri Oct 16 10:03:07 EDT 2009


On Oct 15, 7:07 pm, pjcoup <pjc... at gmail.com> wrote:
> I was fooling around with python's struct lib, looking on how we'd
> unpack some data.  I was a little confused by its behavior:
> Python 2.5.2 (r252:60911, Jul 22 2009, 15:33:10)
> [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import struct
> >>> struct.calcsize('BhhhhB')
> 11
> >>> struct.calcsize('@BhhhhB')
> 11

This result *includes* any necessary padding between two
consecutive fields of the struct (in this case, the extra
byte of padding between the first 'B' and the following
'h', but *excludes* padding at the end of the struct.
The result of struct.pack with one of these formats should
have length exactly 11:  the struct module doesn't bother
including the trailing padding.

> >>> struct.calcsize('<BhhhhB')
> 10
> >>> struct.calcsize('>BhhhhB')
> 10

The non-native formats don't include padding at all.

Mark



More information about the Python-list mailing list