Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 0x0000000200000001 in 64-bit math, and not its exact value (non-overflowing) 0x10000000200000001.

like image 263
Jason S Avatar asked May 25 '13 00:05

Jason S


People also ask

Are Python ints 32 or 64-bit?

There is no such thing in Python. In Python 2, int may be 32-bit or 64-bit, and long is of arbitrary length. You can determine whether a number will fit in 32 or 64 bits, and you can attempt to pack a number into a binary format of suitable size, but that's a quite different question.

How do I get 32-bit integer in Python?

The int data type in python simply the same as the signed integer. A signed integer is a 32-bit integer in the range of -(2^31) = -2147483648 to (2^31) – 1=2147483647 which contains positive or negative numbers.

Does Python use 32-bit integers?

Instead, Python uses a variable number of bits to store integers. For example, 8 bits, 16 bits, 32 bits, 64 bits, 128 bits, and so on. The maximum integer number that Python can represent depends on the memory available.

What is the difference between 32-bit and 64-bit integer?

A 32 bit Signed Integer can house a number from −2,147,483,648 to 2,147,483,647 Unsigned: 0 to 4,294,967,295. A 64 bit Signed Integer can house a number from −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Unsigned: 0 to 18,446,744,073,709,551,615.


2 Answers

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

like image 175
martineau Avatar answered Oct 12 '22 08:10

martineau


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.

like image 44
dawg Avatar answered Oct 12 '22 07:10

dawg