Question: Write a program to count the number of bits that are 1(set bits) in a given integer.
Input:
8 (1000)
11 (1011)
Output:
For 8 – 1 set bit
For 11 – 3 set bits
This question can be done in a very long way where we first convert the integer to its binary form and store its result in a character array. Traversing that character array would give the number of set bits.
But that will not be an efficient way.
We will use bit manipulation to solve this problem.
#include<stdio.h> int bit_count(int num) { int count = 0; while (num > 0) { ++count; num &= (num-1); //clear the least significant bit set } return count; } int main(void) { int ans = bit_count(8); printf("The number of set bits in 8 are = %d",ans); return 0; }
Here num & (num – 1)
will eliminate the rightmost ’1′ in the given number. Each iteration of this will basically remove the rightmost ’1′ digit so we can count the number of 1′s present in the given number.