Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulate uint32_t in Python?

Tags:

python

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?

like image 683
d33tah Avatar asked Oct 07 '13 19:10

d33tah


People also ask

How do I run a 64 bit integer in Python?

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 ]

What is UInt32 Python?

Unsigned integer (0 to 65535) uint32. Unsigned integer (0 to 4294967295) uint64. Unsigned integer (0 to 18446744073709551615)

What is size of int in Python?

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.)

What is unsigned integer in Python?

An unsigned integer is a 32-bit non-negative integer(0 or positive numbers) in the range of 0 to 2^32-1.


1 Answers

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
like image 135
Claudiu Avatar answered Sep 19 '22 13:09

Claudiu