Python: Set Bits Count (popcount) [duplicate]

In Python 3.10+, there is int.bit_count():

>>> 123 .bit_count()
6

Python 2.6 or 3.0:

def bitsoncount(x):
    return bin(x).count('1')

Example:

>>> x = 123
>>> bin(x)
'0b1111011'
>>> bitsoncount(x) 
6

Or

Matt Howells’s answer in Python:

def bitsoncount(i):
    assert 0 <= i < 0x100000000
    i = i - ((i >> 1) & 0x55555555)
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
    return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24

Leave a Comment