python 32-bit and 64-bit integer math with intentional overflow

前端 未结 2 992
忘了有多久
忘了有多久 2021-01-04 03:48

What\'s the best way to do integer math in 32- and 64-bit, so that overflow happens like it does in C?

e.g. (65536*65536+1)*(65536*65536+1) should be 0x0000000200000

相关标签:
2条回答
  • 2021-01-04 04:11

    Use NumPy with the appropriate integer size and the overflow is more C like:

    32 bit:

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

    64 bit:

    >>> i64=np.uint64(65536*65536+1)
    >>> hex(i64*i64)
    '0x200000001L'
    

    Compare with Python's native int:

    >>> hex((65536*65536+1)*(65536*65536+1))
    '0x10000000200000001L'
    

    You can see that NumPy is doing as you desire.

    0 讨论(0)
  • 2021-01-04 04:22

    Just & the result with the appropriate 32- or 64-bit mask (0xffffffff or 0xffffffffffffffff).

    0 讨论(0)
提交回复
热议问题