Friday, April 8, 2011

#C_CODE: Bit Set Count

#include <stdio.h>
 
int bitsetcount(int num)
{
 int i;
 for(i=0; num; i++)
  num &= num - 1;
 return i;
}

int main()
{
 int num;
 printf("Enter the num: ");
 scanf("%d",&num);
 printf("The no. of bits set in %d is: %d\n",num,bitsetcount(num));
 fflush(stdin);
 getchar();
}

Ref: C Programming Language - K&R

No comments: