有意溢出的python 32位和64位整数数学
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16745387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python 32-bit and 64-bit integer math with intentional overflow
提问by Jason S
What's the best way to do integer math in 32- and 64-bit, so that overflow happens like it does in C?
在 32 位和 64 位中进行整数数学运算的最佳方法是什么,以便像在 C 中那样发生溢出?
e.g. (65536*65536+1)*(65536*65536+1) should be 0x0000000200000001 in 64-bit math, and not its exact value (non-overflowing) 0x10000000200000001.
例如 (65536*65536+1)*(65536*65536+1) 在 64 位数学中应该是 0x0000000200000001,而不是它的确切值(非溢出)0x10000000200000001。
采纳答案by martineau
Just &the result with the appropriate 32- or 64-bit mask (0xffffffffor 0xffffffffffffffff).
只是&带有适当的 32 位或 64 位掩码(0xffffffff或0xffffffffffffffff)的结果。
回答by dawg
Use NumPywith the appropriate integer size and the overflow is more C like:
使用具有适当整数大小的NumPy,溢出更像 C:
32 bit:
32 位:
>>> np.uint32(2**32-3) + np.uint32(5)
__main__:1: RuntimeWarning: overflow encountered in uint_scalars
2
64 bit:
64 位:
>>> i64=np.uint64(65536*65536+1)
>>> hex(i64*i64)
'0x200000001L'
Compare with Python's native int:
与 Python 的原生 int 比较:
>>> hex((65536*65536+1)*(65536*65536+1))
'0x10000000200000001L'
You can see that NumPy is doing as you desire.
您可以看到 NumPy 正在按您的意愿行事。

