Python 如何将有符号的 32 位 int 转换为无符号的 32 位 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16452232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:39:39 来源:igfitidea点击:
How to convert signed 32-bit int to unsigned 32-bit int?
提问by Claudiu
This is what I have, currently. Is there any nicer way to do this?
这就是我目前所拥有的。有没有更好的方法来做到这一点?
import struct
def int32_to_uint32(i):
return struct.unpack_from("I", struct.pack("i", i))[0]
采纳答案by martineau
Not sure if it's "nicer" or not...
不确定它是否“更好”...
import ctypes
def int32_to_uint32(i):
return ctypes.c_uint32(i).value
回答by user3181121
using numpy for example:
使用 numpy 例如:
import numpy
result = numpy.uint32( numpy.int32(myval) )
or even on arrays,
甚至在阵列上,
arr = numpy.array(range(10))
result = numpy.uint32( numpy.int32(arr) )

