Checking if an int fits in 32 bits?

Thomas Heller theller at python.net
Thu Dec 4 15:33:43 EST 2008


Roy Smith schrieb:
> 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?
> 

You could try something like this:

import ctypes
def int_fits_in_32bit(value):  
  return ctypes.c_int32(value) == value

and similar for signed/unsigned short/int/long.  Packing and unpacking with
the struct module, however, does basically the same.

Thomas



More information about the Python-list mailing list