Does Python need a '>>>' operator?
David Eppstein
eppstein at ics.uci.edu
Sun Apr 14 23:00:54 EDT 2002
In article <a9dbc9$bge$0 at 216.39.172.122>, bokr at oz.net (Bengt Richter)
wrote:
> All 32-bit ints are represented in hex without a sign, so
This signed-unsigned confusion bit me when I needed a routine to count
the nonzero bits of some input. Normally one would write
def popCount(x):
count = 0
while x:
count += 1
x &= x - 1
but of course this gets into an infinite loop when the high bit is set.
Arguably, this is the correct behavior: a negative number in 2's
complement should be thought of as having an infinite sequence of 1-bits.
But in my case, my input didn't ever have the high bit set, and a good
thing too, or I would have gotten ValueError when I tried
int(hexstring,16).
The reason I was getting into trouble anyway was because of the way
right-shifting can change sign:
>>> 0x40000000<<1
-2147483648
This is inconsistent with int-long unification. In fact, I think it is
a bug. The answer should, of course, be 2147483648L, just as you would
get by multiplying by 2 instead of shifting.
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list