Unsigned integer arithmetic

Robert Cragie rcc at nospamthanks_jennic.com
Wed Apr 26 04:31:14 EDT 2000


Ray&Maria <nospam at nowhere.net> wrote in message
news:PxvN4.1335$sf5.16905 at news.corecomm.net...
| 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)

Nothing at all in principle, but it would be nice to have a neater solution.
I guess I'm showing my C background here, but it would be nicer to have a
notion of unsigned numbers and also to be able to print longs.

I don't like this, as it implies that 'i' is a 32 bit signed integer, but
you don't have any control. It blows up here because it won't extend the
type to a long - as it's typeless, I don't see why it should be able to do
this automatically.

>>> i = 0x7fffffff
>>> i = i + 1
Traceback (innermost last):
  File "<pyshell#1>", line 1, in ?
    i = i + 1
OverflowError: integer addition

Typeless languages are all very well, but there are times when I really
would like to say 'this is a 32 bit unsigned integer - treat it as such'
instead of implied typing. The warning bells sounded a bit on p33 of
'Learning Python' when it suggested that "as a rule of thumb, if you find
yourself wanting to flip bits in Python, you should think long and hard
about which language you're really using". But there are more compelling
reasons why I am using Python than C for my particular application. I don't
particularly want to have to start writing C companion libraries if I can
avoid it.

Robert





More information about the Python-list mailing list