Unpack Expects the Wrong Number of Bytes

Timothy Crone tjcrone at gmail.com
Sat Jul 18 16:34:11 CEST 2009


I have noticed that for certain format strings, struct.unpack expects
the wrong number of bytes. For example, this works fine

header = "4si4s4si2h2i3h4s"
data = list(unpack(header,f.read(42)))

however, this

header = "4si4s4si2h2i3h4si"
data = list(unpack(header,f.read(46)))

returns the following error:

struct.error: unpack requires a string argument of length 48

So even though my format string includes an additional 4-byte integer,
unpack is expecting 6 additional bytes. Here's a simpler example:

This works:

header = "s"
data = list(unpack(header,f.read(1)))

however this:

header = "si"
data = list(unpack(header,f.read(5)))


struct.error: unpack requires a string argument of length 8

So unpack expects 7 additional bytes when an integer is added to the
format string. Does anyone know what is going on? I am using Debian
stable, so my Python version is 2.5.2. But I have replicated this with
2.6.2. Here's my proc/version: Linux version 2.6.30-bpo.1-amd64
(Debian 2.6.30-1~bpo50+1) (nobse at debian.org) (gcc version 4.3.2
(Debian 4.3.2-1.1) ) #1 SMP Fri Jun 26 09:41:55 UTC 2009

Any help would be greatly appreciated.


More information about the Python-list mailing list