Saturday, July 7, 2007

Interesting C Program -4

A Program that counts the number of bits set in a number:


#include "stdio.h"
#include "stdlib.h"
int Count_Bits(int a)
{
int i=0;
int b[10]={0,0,0,0,0,0,0,0,0,0};
int c=0;
while(a!=0)
{
b[i] = a%2;
a = a/2;
i++;
}
for(i=0;i<10;i++)
{
c+=b[i];
}

return c;
}
int main()
{
int x,y;
printf("ENTER A VALUE LESS THAN 1023:");
scanf("%d",&y);
x=Count_Bits(y);
printf("%d",x);
system("pause");
}

The following is another excellent implementation of the same program:

int CountBits(unsigned int x)
{
int count=0;
while(x)
{
count++;
x = x&(x-1);
}
return count;
}

No comments:

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language