Unsigned integer arithmetic
nospam at nowhere.net
Wed Apr 26 07:55:53 CEST 2000
What's wrong with this:
myInt = 0x7fffffff
myLong = long(myInt) #coerce to long
myInt2 = int(myLong) #coerce to int (if it fits)
if n > 0xffffffffL:
print "0x%01x%07x" % (int(n >> 28), int(n & 0xfffffffL))
NOSPAMjchen at NOSPAMquark.com
"Robert Cragie" <rcc at nospamthanks_jennic.com> wrote in message
news:newscache$51sktf$rzc$1 at jenpc07.jennic.co.uk...
> 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,
> want to treat a 32 bit number as an unsigned value, and be able to do 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
> myUlong = struct.unpack('I', struct.pack('l',myInt))
> # unsigned long to integer
> # in the strings, it's a lower case 'ell' and an upper case 'eye' in that
> myInt = struct.unpack('l', struct.pack('I',myUlong))
> 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
> too long to convert'.
> Is there a better way to do all this?
> Robert Cragie
More information about the Python-list