Python Program to count the set bits in a integer

In this simple python program, we need to compute the count of the set bits in an integer. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What are the set bits in the binary number system?

This simple python program is for counting the number of set bits in an integer. In the binary representation of an integer, we use two bits which are 1 and 0, where the 1 is called the set bit. So we have to count the number of set bits in an integer. Let us take an example of number 9; its binary representation is 1001; let us count how many set bits are in that number, that is 2.

How to count all set bits in python?

To apply this logic in python programming, we accept the number from the user, and we are calling a user-defined function to count the number of set bits in that number. Inside that function, we initialize a count variable to zero. Then we open a while loop till the number. Inside that loop, we are using the Bitwise AND operator with n and n-1. When we do Bitwise AND operation between n and n-1, it will remove the last bit. So we are using the count variable to check how many times we are doing this Bitwise AND operation to make the number n to zero. That will be the number of set bits stored in the count, as we increment count in every iteration.


STEP 1: Accept an integer from the user using the input function in the python programming language.

STEP 2: Call the function for counting the number of bits in the number. And print that return value from the function using print in python language.

User-Defined Function countbits(n)

STEP 1: Pass the number to the function as a parameter from the calling function.

STEP 2: Initialize the count variable to zero, which is for counting the set bits.

STEP 3: Open a while loop until the number is zero.

STEP 4: Using bitwise AND operator between the number n and n-1 to remove the last one bit from the number n. continue till the number n is zero.

STEP 5: Increment the count in every iteration of bitwise AND operation, so we get the number of bits in that number by counting the number of times the operation needed to make number zero.

STEP 6: Return the count to the calling function using python basic methods.

Python Source Code

                                          def count_set_bits(n):
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count
num = int(input('Enter number: '))
print("Equivalent Binary Number: ", bin(num)[2:])
print('Number of bits that set in the number:', count_set_bits(num))


Enter number: 12
Equivalent Binary Number:  1100
Number of bits in that set in the number: 2