Python Program to count the set bits in a integer

April 10, 2022, Learn eTutorial

What are the set bits in the binary number system?

In the binary representation of an integer, we use two bits which are 1 and 0, where 1 is called the set bit. So in this python program, we have to count the number of 1's in an integer. Let us take an example of 9; its binary representation is 1001, and the count of '1's' is 2

How to count set bits in python?

To apply this logic in python programming, we accept the integer from the user, and we are calling a user-defined function to count the 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 one bit. 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 count of 1's.


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.

STEP 6: Return and print the count.

To find the count of set bits, we are using the below python topics, please refer those for a better understanding

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 setbits in that set in the number: 2