A. Lloyd Flanagan
alloydflanagan at attbi.com
Thu Mar 6 20:25:49 CET 2003
"Giovanni Bajo" <noway at sorry.com> wrote in message news:<B0J9a.182187$YG2.5523404 at twister1.libero.it>...
> I have some troubles with signed/unsigned integers, probably because it is
> still not clear to me how Python works with respect to this. Especially:
> 1) How can I force 0xFFFFFFFF to be 4294967295 instead of -1? My problem is
> that I'm converting some C code like a = b*c where the result needs to be
> wrapped within 32-bit limits. If I bit-and the result with 4294967295
> everything is ok, but if I use 0xFFFFFFFF the number does not mask
> correctly, because 0xFFFFFFFF is seen as -1. Why should it ever consider a
> hex literal as negative, by the way? Is there any real-world case where this
> is needed?
Remember that python 'plain' integers are always signed 32-bit values.
Anything that won't fit in that has to be a 'long' integer, which can
be any size. Currently, the interpreter fits a hex constant into a
'plain' integer if it can, even if it means changing sign.
You're not the first to suggest this is a bad idea. As of python 2.4,
0xFFFFFFFF will in fact be a positive (long) integer.
For versions < 2.4, you have to write 0xFFFFFFFFL to force the
constant to interpreted as a long.
> 2) binascii.crc32() returns a signed integer representing the CRC. I call it
> signed because if I print the result it displays a signed number. Now, what
> if I need the unsigned representation of it (as in, the unsigned number
> which is machine-represented with the same 32 bits)? I need to multiply it
> by another integer, but I need an unsigned multiplication, not a signed one.
I think you'd have to do:
if x < 0:
x = 0xFFFFFFFFL + x + 1
or if PEP 308 gets adopted, something like :
(x if x >= 0 else 0xFFFFFFFFL + x + 1) #:)
More information about the Python-list