top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

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

+5 votes
137 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
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...