Unsigned integer arithmetic
Robert Cragie
rcc at nospamthanks_jennic.com
Tue Apr 25 09:53:28 EDT 2000
Hi all,
I'm having a lot of trouble with arithmetic manipulation of numbers above
0x7fffffff. Whilst an integer is represented in a 32 bit word, as you'd
expect, 0x80000000 - 0xffffffff are treated as negative numbers. However, I
want to treat a 32 bit number as an unsigned value, and be able to do i = i
+ 1 for an integer number above 0x7fffffff without getting an overflow.
I'm finding I have to use the inefficient longs for the arithmetic, and do
clumsy conversions using the struct module, e.g.
import struct
# integer to unsigned long
# in the strings, it's an upper case 'eye' and a lower case 'ell' in that
order
myUlong = struct.unpack('I', struct.pack('l',myInt))[0]
# unsigned long to integer
# in the strings, it's a lower case 'ell' and an upper case 'eye' in that
order
myInt = struct.unpack('l', struct.pack('I',myUlong))[0]
Also, I can't seem to print a long using
print '0x%08x' % myLong
if 'myLong' is greater than 0x7fffffff - I get the rather obscure 'long int
too long to convert'.
Is there a better way to do all this?
TIA
Robert Cragie
More information about the Python-list
mailing list