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
Answer from Claudiu on Stack OverflowYou 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
Here's an interesting solution, though it only works under Python 2:
class U32:
"""Emulates 32-bit unsigned int known from C programming language."""
def __init__(self, num=0, base=None):
"""Creates the U32 object.
Args:
num: the integer/string to use as the initial state
base: the base of the integer use if the num given was a string
"""
if base is None:
self.int_ = int(num) % 2**32
else:
self.int_ = int(num, base) % 2**32
def __coerce__(self, ignored):
return None
def __str__(self):
return "<U32 instance at 0x%x, int=%d>" % (id(self), self.int_)
def __getattr__(self, attribute_name):
print("getattr called, attribute_name=%s" % attribute_name)
# you might want to take a look here:
# https://stackoverflow.com/q/19611001/1091116
r = getattr(self.int_, attribute_name)
if callable(r): # return a wrapper if integer's function was requested
def f(*args, **kwargs):
if args and isinstance(args[0], U32):
args = (args[0].int_, ) + args[1:]
ret = r(*args, **kwargs)
if ret is NotImplemented:
return ret
if attribute_name in ['__str__', '__repr__', '__index__']:
return ret
ret %= 2**32
return U32(ret)
return f
return r
print(U32(4) / 2)
print(4 / U32(2))
print(U32(4) / U32(2))
For Python 3 compatibility, have a look here.
Converting hex to uint32
Fixed width integer types (e.g. uint32) in Python - Stack Overflow
Newest 'uint32' Questions - Stack Overflow
python - How to convert signed 32-bit int to unsigned 32-bit int? - Stack Overflow
Please help me with data type conversion. I have binary file which I read as bytes. I am able to convert data into hex and decimal but unable to convert into unsigned int 32.
For interfacing with hardware we normally use the struct standard library - specifically struct.pack and struct.unpack not only are fixed widths handled but also endianess issues. See the python 2 or python 3 library manuals.
Once you have retrieved your data from your hardware and unpacked it if you are going to be performing any heavy duty mathematics on it you would usually assign it to numpy data types which will:
- Provide just about any operation that you could need,
- Behave as expected for the data type
- If you have lots of data stored in arrays or matrices provide vector methods for handling the data quickly & simply.
import numpy as np
x = np.uint32(42)
print(x << 20) # 44040192
print(x << 32) # 180388626432 - Looks like it has been promoted
print(type(x << 32)) # numpy.int64 - it has
So if you are doing something such as reading a set of A-D readings from registers and then performing a lot of maths on them so as to produce a graph, etc. then this is fine but if you are reading a value from one register, doing some math, then writing the results back to a register you need to take care using anything like numpy.
Note that there is also the ctypes library available for interfacing with hardware and DLLs but it will always expect the values to be in "native" format - so, for example, if you are reading a 16 bit number from big endian hardware on a little endian machine then you will get problems.
I would suggest the fixedint library. The classes in that library are named in the following convention:
[Mutable][U]Int<N>
So for your two examples, the classes would be
# C++ Python fixedint
std::uint32 UInt32
std::uint16 UInt16
This supports things like bit-shifting, etc
>>> a = fixedint.UInt32(14)
>>> a
UInt32(14)
>>> a << 2
UInt32(56)
Not sure if it's "nicer" or not...
import ctypes
def int32_to_uint32(i):
return ctypes.c_uint32(i).value
using numpy for example:
import numpy
result = numpy.uint32( numpy.int32(myval) )
or even on arrays,
arr = numpy.array(range(10))
result = numpy.uint32( numpy.int32(arr) )