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!

2
  • You could do a simple (if a > 2147483647) a -= 232 and (if b < - 2147483648) b += 232 whenever you change a or b. Commented Sep 13, 2013 at 3: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. Commented Sep 13, 2013 at 3:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.