Python:让Python的整数溢出像C整数一样。

10
在Python中,当一个整数大于2**31时,它将会变成长整型:

a = 2147483647 a + 1 = 2147483648

b = -2147483648 b - 1 = -2147483649

但我需要像C语言中的int一样发生Python整数溢出:

a = 2147483647 a + 1 = -2147483648

b = -2147483648 b - 1 = 2147483647

是否可能?谢谢!

每当更改a或b时,您可以执行以下操作:如果a > 2147483647,则执行简单操作a -= 2 ** 32;如果b < - 2147483648,则执行操作b += 2 ** 32。 - CamelopardalisRex
我认为没有简单的方法可以做到这一点,因为整数就是按照这种方式设计的。Alex的想法似乎不错。 - rslite
2个回答

6

尝试使用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'>

确保在将这些对象传递给期望正常Python溢出行为的代码之前,对它们调用int


3
你可以定义自己的类并覆盖__int__()特殊方法,以及其他各种数学运算符特殊方法,来模拟数字类型。然后你的类可以保持不变量,即值始终在适当范围内。
例如:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接