Checking if an int fits in 32 bits?

Jean-Paul Calderone exarkun at divmod.com
Thu Dec 4 17:32:30 EST 2008


On Thu, 4 Dec 2008 12:11:08 -0800 (PST), Roy Smith <roy at panix.com> wrote:
>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?

How about simple bounds checking?  An integer fits in an unsigned 32bit
representation if it is greater than or equal to 0 and less than 2 ** 32.
The bounds for the sizes are similarly simple to determine and check.

Jean-Paul



More information about the Python-list mailing list