Overflow-less integer arithmetic?

Erik Max Francis max at alcyone.com
Mon Aug 20 02:03:24 EDT 2001


I'm working on an application where I need arithmetic to be done modulo
2^32 (actually, often it will be 2^n with n < 32).  Python (very nicely)
throws OverflowErrors when an arithmetic calculation breaks these
bounds, but this is one rare case where I'd prefer it not to happen. 
Essentially I'd like things to behave just as if you had a signed 32-bit
two's-complement number.

What is the standard Pythonic way to accomplish this?  The obvious thing
(catching the OverflowError and then doing the computation in longs and
converting back) didn't seem to work, since the obvious bitmask didn't
do the job, since obviously the bitwise and operator doesn't have quite
the same meaning for longs:

max at oxygen:~% python
Python 2.0 (#2, Apr  4 2001, 19:28:30) 
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> i = 2147483648l # one greater than the largest int
>>> i
2147483648L
>>> i & 0xffffffff
2147483648L # whoops

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ It's just another day / And nothing's any good
\__/ Sade
    Alcyone Systems / http://www.alcyone.com/
 Alcyone Systems, San Jose, California.



More information about the Python-list mailing list