10

In Python, when a int bigger than 2**31, then it will turn to a long:

a = 2147483647 a + 1 = 2147483648

b = -2147483648 b - 1 = -2147483649

but I need the Python int overflow like the int in C:

a = 2147483647 a + 1 = -2147483648

b = -2147483648 b - 1 = 2147483647

Is it possible? thanks in advance!

CamelopardalisRex
  • 353
  • 1
  • 2
  • 16
Charlie Lin
  • 1,613
  • 2
  • 13
  • 16
  • You could do a simple (if a > 2147483647) a -= 2**32 and (if b < - 2147483648) b += 2**32 whenever you change a or b. – CamelopardalisRex Sep 13 '13 at 03:20
  • I don't think there is an easy way to do it since that's the way the integers were designed to work. Alex's idea seems a good one. – rslite Sep 13 '13 at 03:28

2 Answers2

6

Try numpy:

>>> x = numpy.int32(2147483647)
>>> x
2147483647
>>> type(x)
<type 'numpy.int32'>
>>> x+1
__main__:1: RuntimeWarning: overflow encountered in long_scalars
-2147483648
>>> type(x+1)
<type 'numpy.int32'>

Just make sure to call int on these things before passing them to code that expects normal Python overflow behavior.

user2357112
  • 260,549
  • 28
  • 431
  • 505
3

You can define your own class and override the __int__() special method, along with various other mathematical operator special methods, to emulate a numeric type. Then your class can maintain the invariant that the value is always in the proper range.

For example:

def class Int32:
    def __init__(self):
        self.value = 0

    def __init__(self, value):
        # Wrap value into [-2**31, 2**31-1]
        self.value = (value + 2**31) % 2**32 - 2**31

    def __int__(self):
        return self.value

    def __add__(self, other):
       return Int32(self.value + other.value)

    # ... etc. for other mathematical operators
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589