top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Write a function that determines the number of bits set to 1 in the binary representation of an integer.

+5 votes
507 views
Write a function that determines the number of bits set to 1 in the binary representation of an integer.
posted Jan 7, 2014 by Sandeep

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

Check if you are looking for bitcount in the following way...

#include <stdio.h>

int bitcount(int n) 
{
  int counter = 0;
  while(n) {
    counter ++;
    n &= (n - 1);
  }
  return counter;
}

main()
{
  int i;

  for(i=0;i<20;i++)
    printf("0x%x -- %d\n", i, bitcount(i));
}
answer Jan 7, 2014 by Amit Mishra
...