# Unsigned integer arithmetic

Ray&Maria 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)

def printU32Hex(n):
if n > 0xffffffffL:
raise ValueError
print "0x%01x%07x" % (int(n >> 28), int(n & 0xfffffffL))

printU32Hex(0x7fffffffL)
printU32Hex(0xffffffffL)
printU32Hex(0x100000000L)

Ray
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,
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
>
>
>

```