Python 2 has two integer datatypes int
and long
, and automatically converts between them as necessary, especially in order to avoid integer overflow.
I am simulating a C function in Python and am wondering if there are standard ways to re-enable integer overflow. For the nonce, I've used
overflow_point = maxint + 1
if value > overflow_point:
value -= 2 * overflow_point
Is there a more standard way to do the same thing?
Use NumPy (which is written in C and exposes native machine-level integers). NumPy has these integer types:
Signed integers:
Unsigned integers:
For example (notice it overflows after integer value 127):
import numpy as np
counter = np.int8(0)
one = np.int8(1)
for i in range(130):
print(type(counter), counter)
counter = counter + one
At any point you can convert back to a Python integer with just int(counter)
, for example.
I think the basic idea is sound, but needs some tweaks:
sys.maxint+1
, but it should;sys.maxint
can be exceeded several times over as a result of a single operation;-sys.maxint-1
also need to be considered.With this in mind, I came up with the following:
import sys
def int_overflow(val):
if not -sys.maxint-1 <= val <= sys.maxint:
val = (val + (sys.maxint + 1)) % (2 * (sys.maxint + 1)) - sys.maxint - 1
return val
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With