Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,051 questions

40,769 answers

573 users

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 80 views
1 answer 74 views
1 answer 77 views
2 answers 83 views
1 answer 73 views
73 views asked May 9, 2019 by avibootz
...