struct.calcsize() giving odd results

John Purser NO_SPAM_jmpurser2 at attbi.com
Tue Mar 12 18:05:35 EST 2002


I'm reading from a binary file with a 180 byte record length.  I created a
format string using a seriously long stiring made up of:
x
c
h
i
15s, 31s, 2s

And that's it.  I tucked this into a variable (fmt) and ran it through
struct.calcsize(fmt) and got 190.  I assumed I'd made a typo so I went over
my string.  No problems there.  So I assumed I added it up wrong in the
first place.  Nope, 180 bytes.  I checked each charachter with
struct.calcsize() to be sure it was giving the expected value.  It was.
Then I started removing charachters from the end of my format string.  The
first two 'c's reduced the count to 188 as expected.  Then I removed an 'i'
and the count dropped to 181!!!

I took out another 'i' and the count dropped to 177.  I've duplicated this
on Debian Linux (Python 2.1) and Windows 2000 (Python 2.2) using the Idle
interactive shell.  Can anyone tell me what I'm doing wrong or is this a
known bug?  I'm new to python and working on my first project so I'd really
appreciate the help.

John Purser

Idle session snapshot:

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import struct
>>> dog = 'x i 15s 15s 15s 15s 31s 2s c c c c c i i i i h i i i 31s c i c c
c c c i c c'
>>> struct.calcsize(dog)
190
>>> dog = 'x i 15s 15s 15s 15s 31s 2s c c c c c i i i i h i i i 31s c i c c
c c c i'
>>> struct.calcsize(dog)
188
>>> dog = 'x i 15s 15s 15s 15s 31s 2s c c c c c i i i i h i i i 31s c i c c
c c c'
>>> struct.calcsize(dog)
181
>>>





More information about the Python-list mailing list