Checking if an int fits in 32 bits?

John Machin sjmachin at lexicon.net
Thu Dec 4 18:11:16 EST 2008


On Dec 5, 7:11 am, Roy Smith <r... at panix.com> wrote:

> At first I thought pack() might raise an exception on a value
> overflow, that but doesn't seem to be the case:
>
> >>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)]
>
> ['0xde', '0x9f', '0xff', '0xff']

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on win32
>>> import struct
>>> [hex(ord(c)) for c in struct.pack('!i', 999999999999999999999L)]
__main__:1: DeprecationWarning: struct integer overflow masking is
deprecated
['0xde', '0x9f', '0xff', '0xff']

You must be using an older version of Python.

I'd go with Jean-Paul's suggestion of (inline no-function-call-
overhead portable no-bit-twiddling) bounds checking.

Cheers,
John



More information about the Python-list mailing list