Count the number of bits set in an Integer using C

Problem : Write a best approach to count the number of bits set in given integer number using C.

Understanding : All the numbers can be represented in Binary Format. For example Number 5 can be represented as 0101.

Our program should take number 5 as number and count the number of bits set and print the number of bits set in Binary representation of 5 : 0101.

In example where input is 5, the program should return 2.

Let us see few more examples:

Example 1:
      Input number = 10 
      Output = 2 
      Binary representation of 10 is 1010 
Example 2:
      Input number = 103
      Output = 5 
      Binary representation of 103 is 1100111


Method 1 :

One of the easiest method is the loop through all the bits of integer and check whether bit is set of not. Based on whether the number is set, we will update the counter and print the counter

// C program to Count set bits in an integer
#include <stdio.h>

int main()
{
    int n = 103;
    unsigned int count = 0;
    
    /*Loop through number becomes 0*/
    while (n) {
        /*Update the count when the 0th bit is set*/
        count += n & 1;
        /*Right shift by 1 to remove rightmost bit*/
        n >>= 1;
    }
    
    printf("\r\nNumber of bits set = %d", count);
    return 0;
}

Output:

Number of bits set = 5

Footnotes:

To know more about Binary Numbers : https://en.wikipedia.org/wiki/Binary_number

Leave a Comment