[C] 計算有幾個位元為 1

  • 3592
  • 0
  • 2013-08-02

計算有幾個位元為 1

 


#include <stdio.h>
#include <string.h> 

int countbits(int value)
{
    int count=0,i;
    int bits = sizeof(value)*8;
    for(i=0;i<bits;i++)
    {
        if(value&1)
            count++;
        value >>=1;
    }
    return count;
} 

int main()
{
    int input; 

    scanf("%d",&input); 

    printf("count = %d\n",countbits(input)); 

    return 0; 

}