Checking if an int fits in 32 bits?

Roy Smith roy at panix.com
Thu Dec 4 15:11:08 EST 2008


I'm working with marshaling data over a binary wire protocol.  I'm
using struct.pack() to handle the low-level encoding of ints.  One of
the things I need to do is make sure an int can be represented in 4
bytes.  Is there a portable way to do that?  For now, I'm doing signed
ints, but I'll certainly have to do unsigned 32-bit ints (and 64-bit
ints) at some point.  Not to mention shorts and chars.

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']

Should I be thinking more along the lines of bit masking (and worrying
about all the niggling 2-complement issues) in the Python code?  Or is
there some cleaner way to do this?




More information about the Python-list mailing list