[Python-Dev] Unclear on the way forward with unsigned integers

Mark Hammond mhammond@skippinet.com.au
Mon, 7 Oct 2002 09:39:17 +1000


I'm a little confused by the new world order for working with integers in
extension modules.

At the end of the day, my question is this:

Assume my extension module has an unsigned integer it wishes to return to
Python.  Further, assume that this unsigned integer is not really an integer
as such, but more a set of bits, or some other value "encoded" in 32 bits,
such as an enum. (To put it another way, the "signedness" of this value
seems more random than chosen)

How should I create the object to return to Python?

For a concrete example.  Let's say I want to return the value of the Win32
function GetVersion().

The documentation for this function declares it is an unsigned 32 bit value.
The documentation then explains that to decode this value, specific bits in
the value should be examined.  It then expounds on this with C sample code
that relies on this unsigned behaviour by using a simple "> 0x80000000"
comparison to check the high bit!

I see 2 choices for returning this value:

* Use PyInt_FromLong() - this will give me a *signed* Python integer, but
with an identical bit pattern.

* Use PyLong_FromUnsignedLong() - this function will correctly be signed,
but may no longer fit in 32 bits.

Now, I think I am trying to stay too close to the hardware for a language
like Python, but something just seems wrong with promoting my nice 32 bit
value to a Python long, simply for the sake of retaining the sign for a
value that the whole concept of "signed" doesn't make much sense (as it
doesn't in this case, or in the case of enums etc).

Any suggestions or general advice?  While this case seems quite trivial, I
am starting to face this issue more and more, especially as I am seeing
these lovely "FutureWarnings" from all my lovely 32 bit hexadecimal
constants <wink/frown>

Thanks,

Mark.