ProAnswers.org

Count the number of set bits in a number

Write a function to count the number of 1 bits appearing in the binary representation of an integer?

	int count_bit(int x)

	{

	 int count;

	 for(count = 0; x != 0; x = x >> 1)

	     if(x & 1)  //& is the BITWISE AND operator

	         count++;

	 return count;

	}