Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Bug in struct.pack?

Reply
Thread Tools

Bug in struct.pack?

 
 
Alex Stapleton
Guest
Posts: n/a
 
      01-11-2006
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.

Also.

>>> calcsize('BL')

8
>>> calcsize('BBL')

8
>>> calcsize('BBBL')

8
>>> calcsize('BBBBL')

8
>>> calcsize('BBBBBL')

12
>>> pack("BBBL", 255,255,255,0)

'\xff\xff\xff\x00\x00\x00\x00\x00' ####### That's 3 255's and 5(!?!?)
0's
>>> pack("BBBBL", 255,255,255,255,0)

'\xff\xff\xff\xff\x00\x00\x00\x00' ######### 4 255's and 4 0's!

Which is all kinds of wrong.

BL should be 9
BBL should be 10
.....

Python 2.4.1 (#2, May 5 2005, 11:32:06)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2

Same behaviour on my PowerBook using

Python 2.3.5 (#1, Mar 20 2005, 20:38:20)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin

sizeof(unsigned long) should be 8 on both of these platforms
sizeof(unsigned char) should be 1 on both as well

So am I just being stupid and not specifying something I should be?
Or is struct really that broken?
 
Reply With Quote
 
 
 
 
Raymond Hettinger
Guest
Posts: n/a
 
      01-11-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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
*bug* *bug* *bug* David Raleigh Arnold Firefox 12 04-02-2007 03:13 AM
ASP.NET Login control bug or SQL 2005 bug? RedEye ASP .Net 2 12-13-2005 10:57 AM
Re: BUG? OR NOT A BUG? John ASP .Net 2 09-21-2005 10:31 AM
Bug Parade Bug 4953793 Michel Joly de Lotbiniere Java 4 12-02-2003 05:05 AM
how to report bug to g++ ? got a bug and fixed up source code DarkSpy C++ 4 06-27-2003 09:05 AM



Advertisments