How to count set bits of an integer in C

1 Answer

0 votes
#include <stdio.h> 
   
unsigned int count_set_bits(unsigned int n) { 
    unsigned int count = 0; 
    while (n) { 
        count += n & 1; 
        n >>= 1; 
    } 
    return count; 
}  

int main() 
{ 
    int n = 45; // 00101101
    
    printf("%i", count_set_bits(n)); 
     
    return 0; 
} 
 
 
 
/*
run:
 
4
 
*/

 



answered May 8, 2019 by avibootz
edited May 9, 2019 by avibootz

Related questions

1 answer 118 views
1 answer 75 views
2 answers 96 views
2 answers 87 views
1 answer 76 views
1 answer 63 views
2 answers 84 views
...