struct.pack bug?

John Machin sjmachin at lexicon.net
Thu Feb 8 20:11:21 EST 2007


On Feb 9, 8:58 am, Jonathan Fine <j... at pytex.org> wrote:
> Hello
>
> I find the following inconsistent:
> ===
>  >>> sys.version
> '2.4.1a0 (#2, Feb  9 2005, 12:50:04) \n[GCC 3.3.5 (Debian 1:3.3.5-8)]'
>  >>> pack('>B', 256)
> '\x00'
>  >>> pack('<B', 256)
> '\x00'
>  >>> pack('B', 256)
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> struct.error: ubyte format requires 0<=number<=255
>  >>>
> ===
>
> I was hoping that '>B' and '<B' would raise an exception,
> ust as 'B' does.
>
> On Oct 27 2006, 11:17 am, Jansson Christer reported a
> different anomoly to this newsgroup, using the same
> subject.

Your Python is out-of-date in two dimensions: the 2.4 series is way
past 2.4.1, and Python 2.5 has been out for a while.

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
| >>> from struct import pack
| >>> pack('<B', 256)
| __main__:1: DeprecationWarning: 'B' format requires 0 <= number <=
255
| '\x00'

Until the deprecation warning becomes an exception in 2.6, I'd suggest
doing your own checking:
assert 0 <= pack_B_candidate <= 255

HTH,
John




More information about the Python-list mailing list