faqts : Computers : Programming : Languages : Python : Snippets : Maths

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

16 of 24 people (67%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I count the number bits in a number?

Jul 5th, 2000 10:00
Nathan Wallace, unknown unknown, Hans Nowak, Snippet 104, Klaus Alexander Seistrup


"""
Packages: maths.bit_twiddling
"""
"""
G'day mates.
Here's a snippet for the repository:
"""
# The function bitcount() will count the number
# of bits in a number, iterating at most as many
# times as the number of bits.
#
def bitcount(x):
    n = 0
    while x:
        x = x & (x-1)
        n = n + 1
    # end while
    return n
# end def bitcount