如何将带符号的32位int转换为无符号的32位int?

Cla*_*diu 9 python unsigned signed integer type-conversion

这就是我现在所拥有的.有没有更好的方法来做到这一点?

import struct
def int32_to_uint32(i):
    return struct.unpack_from("I", struct.pack("i", i))[0]
Run Code Online (Sandbox Code Playgroud)

mar*_*eau 19

不确定它是否"更好"或不......

import ctypes

def int32_to_uint32(i):
    return ctypes.c_uint32(i).value
Run Code Online (Sandbox Code Playgroud)


小智 6

以numpy为例:

import numpy
result = numpy.uint32( numpy.int32(myval) )
Run Code Online (Sandbox Code Playgroud)

甚至在阵列上

arr = numpy.array(range(10))
result = numpy.uint32( numpy.int32(arr) )
Run Code Online (Sandbox Code Playgroud)