I was trying to port a function from C to Python and to make it easy to debug, I'd prefer it performed the same CPU word-size limited operations so I could compare the intermediate results. In other words, I'd like something like:
a = UnsignedBoundedInt(32, 399999)
b = UnsignedBoundedInt(32, 399999)
print(a*b) # prints 1085410049 (159999200001 % 2**32)
What's the best way to achieve this so that all operations (including bitwise shifts) would work as in C?
Similarly, if you want to use 16 bits, 32 bits, and 64 bits to store integers, the ranges would be: 16-bits ~ [-215, 215 – 1] = [ -32,768 , 32,767 ] 32-bits ~ [-231, 231 – 1] = [- 2,147,483,648 , 2,147,483,647 ] 64-bits ~ [-263, 263 – 1] = [ -9,223,372,036,854,775,808 , 9,223,372,036,854,775,807 ]
Unsigned integer (0 to 65535) uint32. Unsigned integer (0 to 4294967295) uint64. Unsigned integer (0 to 18446744073709551615)
These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.)
An unsigned integer is a 32-bit non-negative integer(0 or positive numbers) in the range of 0 to 2^32-1.
You can try using ctypes.uint_32
to bound the results for you:
>>> import ctypes
>>> print ctypes.c_uint32(399999 * 399999).value
1085410049
Alternatively you can use numpy's data types:
>>> import numpy as np
>>> a = np.uint32(399999)
>>> b = np.uint32(399999)
>>> a * b
__main__:1: RuntimeWarning: overflow encountered in uint_scalars
1085410049
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With