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

后端 未结 3 469
既然无缘
既然无缘 2021-01-02 07:05

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         


        
相关标签:
3条回答
  • 2021-01-02 07:45

    I just started learning python, but something simple like this works for values in the range of a signed 32-bit integer

    def uint(x):
      if x < 0:
        return hex(0xffff_ffff - abs(x) + 1)
      else:
        return hex(x)
    
    0 讨论(0)
  • 2021-01-02 07:58

    Not sure if it's "nicer" or not...

    import ctypes
    
    def int32_to_uint32(i):
        return ctypes.c_uint32(i).value
    
    0 讨论(0)
  • 2021-01-02 08:04

    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) )
    
    0 讨论(0)
提交回复
热议问题