How to convert a signed 32-bit int to an unsigned 32-bit int?

This is what I have, now. Is there a better way to do this?

import struct def int32_to_uint32(i): return struct.unpack_from("I", struct.pack("i", i))[0] 
+8
python type-conversion integer unsigned signed
source share
2 answers

Not sure if this is "better" or not ...

 import ctypes def int32_to_uint32(i): return ctypes.c_uint32(i).value 
+17
source share

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) ) 
+3
source share

All Articles