Thursday, February 9, 2012

C Program to count the number of ones in a 32 bit number.

#include<stdio.h>

int bitcount(unsigned int n)
{
  int count=0;
  while(n)
  {
      count+=n& 0x1u;
      n>>=1;
  }
  return count;
}

void main()
{
     unsigned int g;   int n;
    printf(" \n Enter the number : \n");
    scanf("%u",&g);
    n=bitcount(g);
  printf("It has %d ones",n);
 }

eg:

Enter the number:
7

It has 3 ones

No comments:

Post a Comment