具有故意溢出的python 32位和64位整数数学

Jas*_*n S 14 python integer-math

在32位和64位中进行整数数学运算的最佳方法是什么,这样溢出就像在C中一样?

例如(65536*65536 + 1)*(65536*65536 + 1)在64位数学运算中应为0x0000000200000001,而不是其精确值(非溢出)0x10000000200000001.

mar*_*eau 23

只是&使用适当的32位或64位掩码(0xffffffff0xffffffffffffffff)的结果.


daw*_*awg 15

使用具有适当整数大小的NumPy,溢出更像C:

32位:

>>> np.uint32(2**32-3) + np.uint32(5)
__main__:1: RuntimeWarning: overflow encountered in uint_scalars
2
Run Code Online (Sandbox Code Playgroud)

64位:

>>> i64=np.uint64(65536*65536+1)
>>> hex(i64*i64)
'0x200000001L'
Run Code Online (Sandbox Code Playgroud)

与Python的native int比较:

>>> hex((65536*65536+1)*(65536*65536+1))
'0x10000000200000001L'
Run Code Online (Sandbox Code Playgroud)

你可以看到NumPy正在按你的意愿行事.