Pythonic bit twiddling

David Eppstein eppstein at ics.uci.edu
Fri Feb 22 03:18:59 EST 2002


In article <7xd6yyfdep.fsf at ruckus.brouhaha.com>,
 Paul Rubin <phr-n2002a at nightsong.com> wrote:

> Am I missing something?  Python has the usual bit operations that work
> on ints.

I found the automatic integer-long conversions messed up some C idioms for 
bit twiddling:

# wrong way to count number of nonzero bits in a <=32-bit integer
def countBits(x):
        i = 0
        while x != 0:
                x &= x - 1
                i += 1
        return i

# better
def countBits(x):
        i = 0
        if (x < 0):   # prevent infinite loop from int->long autoconversion
                x ^= (1<<31)
                i = 1
        while x != 0:
                x &= x - 1
                i += 1
        return i
-- 
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