Count the Number of 1 Bits in Python: int.bit_count

Modified: | Tags: Python, Numeric

This article explains how to count the number of 1s in the binary representation of an integer int in Python. This operation is also known as popcount or population count.

See the following articles for more information on the binary representation and bitwise operations in Python.

int.bit_count() (Python 3.10 or later)

Python 3.10 introduced the bit_count() method.

i = 100
print(bin(i))
# 0b1100100

print(i.bit_count())
# 3

i = 255
print(bin(i))
# 0b11111111

print(i.bit_count())
# 8

As described in the official documentation, bit_count() returns the number of 1s in the binary representation of the absolute value of the integer.

Return the number of ones in the binary representation of the absolute value of the integer. Built-in Types - int.bit_count() — Python 3.11.3 documentation

i = -100
print(bin(i))
# -0b1100100

print(i.bit_count())
# 3

i = -255
print(bin(i))
# -0b11111111

print(i.bit_count())
# 8

As demonstrated in the example above, the output of bin() is simply the absolute value prefixed by a minus sign. If you want to obtain a string represented in two's complement form, see the following article.

bin(self).count("1") (Python 3.9 or earlier)

In Python 3.9 or earlier, the bit_count() method is not provided. However, you can achieve an equivalent operation using bin(self).count("1") as described in the official documentation.

The built-in bin() function can be used to convert an integer int to a binary notation string, and the count() method can then be used to count characters in the string.

def bit_count(self):
    return bin(self).count("1")

print(bit_count(100))
# 3

print(bit_count(255))
# 8

print(bit_count(-100))
# 3

print(bit_count(-255))
# 8

Note that the bit_count() method introduced in Python 3.10 does not use bin() and count(). Instead, it uses an efficient algorithm implemented in C, making it faster.

The following code uses the Jupyter Notebook magic command %%timeit. Note that this will not work if run as a Python script.

i = 255

%%timeit
i.bit_count()
# 22 ns ± 0.072 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

%%timeit
bit_count(i)
# 121 ns ± 0.275 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

Related Categories

Related Articles