question on struct.calcsize

David Bolen db3l at fitlinxx.com
Thu Mar 28 15:33:30 EST 2002


stojek at part-gmbh.de (Marcus Stojek) writes:

> Hi,
> could anyone explain the following, please.
> (Win NT, Python 2.1.1)
> 
> >>> from struct import *
> >>> calcsize("i")
> 4
> >>> calcsize("s")
> 1
> >>> calcsize("si")
> 8

Padding.  When forming a structure, the default will be to add
inter-field padding as dictated by the local compiler/implementation
to improve numeric alignment.  In many cases that will be a 4-byte
(32-bit) boundary for numeric values.  So in your second case, in
order to get the integer aligned on a 4-byte boundary, it padded out
the character.  Note that if you flip the order, you won't need the
alignment (shown below).

The default padding is "native" (implementation specific) but you can
ask for standard alignment which does no padding.  The first character
of each format string can control byte ordering/alignment.  If you use
"=" you'll get standard alignment while not affecting byte order
(which will still be based on your native platform).  Other characters
(<, >, !) control byte ordering in addition to alignment.

Thus:

    Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license" for more information.
    >>> from struct import *
    >>> calcsize("i")
    4
    >>> calcsize("s")
    1
    >>> calcsize("si")
    8
    >>> calcsize("is")
    5
    >>> calcsize("=si")
    5

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list