13

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]
0

3 Answers 3

29

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

import ctypes

def int32_to_uint32(i):
    return ctypes.c_uint32(i).value
Sign up to request clarification or add additional context in comments.

8 Comments

That returns a Python integer type, though, which probably isn't a meaningful result in this context, as it isn't actually a uint32 anymore. I suppose it depends on how he's using it.
@Cairnarvon: For 1 and -1, the OP's version returns an int and a long respectively. My version returns a long for both.
Nice! I'd probably prefer this. Is this as cross-platform as struct?
@Claudiu: As for cross-platformness, all I can say is I think so.
@Claudiu: FWIW, in Python 3.3 both your and my version return int for both cases. Also, what's the basis of your preference? You've never said what sort of nicer you're after.
|
7

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) )

Comments

0

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)

2 Comments

why would you EVER need an unsigned int in the range of a signed int?
There are a lot of scenarios where you want to cast signed to unsigned. Sometimes its necessary when working directly registers on hardware device. If I remember correctly what I was doing at the time is that I wanted the hex representation for display purposes. If you, said print(x) you got -1, but I wanted to show the twos-complement hex value of 0xFFFF_FFFF.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.