Home Misc Count number of bits that are 1 in a given Integer

Count number of bits that are 1 in a given Integer

by nikoo28
0 comment 2 minutes read

Question: Write a program to count the number of bits that are 1(set bits) in a given integer.

8 (1000)

11 (1011)
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.


int bit_count(int num)
	int count = 0;
	while (num > 0)
		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.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More