11

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]
martineau
  • 119,623
  • 25
  • 170
  • 301
Claudiu
  • 224,032
  • 165
  • 485
  • 680

3 Answers3

25

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

import ctypes

def int32_to_uint32(i):
    return ctypes.c_uint32(i).value
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 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 May 09 '13 at 01:50
  • @Cairnarvon: For `1` and `-1`, the OP's version returns an `int` and a `long` respectively. My version returns a `long` for both. – martineau May 09 '13 at 03:47
  • Nice! I'd probably prefer this. Is this as cross-platform as `struct`? – Claudiu May 09 '13 at 14:53
  • @Claudiu: As for cross-platformness, all I can say is I think so. – martineau May 09 '13 at 18:00
  • @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. – martineau May 09 '13 at 18:11
  • By "nicer" I meant "more pythonic". I'm not sure what that would be in this case. But it seemed hackish to pack it into a one-member struct and then to read it back out. This does essentially the same but it's a bit clearer, and doesn't require an array index. – Claudiu May 09 '13 at 18:44
  • @Claudiu: I see. If you change my answer to `return int(ctypes.c_uint32(i).value)` it will return `int` and `long` for the two cases like your `struct` version does -- which is better in that it makes more sense in my opinion. – martineau May 09 '13 at 19:15
  • Accepting this. I like it as it makes it more obvious what the code does. – Claudiu May 21 '13 at 16:16
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) )
user3181121
  • 119
  • 1
  • 2
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)
Darrel Lee
  • 2,372
  • 22
  • 22
  • why would you EVER need an unsigned int in the range of a signed int? – GoldenretriverYT Apr 19 '22 at 11:00
  • 2
    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. – Darrel Lee Apr 22 '22 at 16:20