How to count the bits in a char with C

1 Answer

0 votes
#include <stdio.h>

int countCharBits(char ch) { 
    int i = 0; 
	
    while (ch) { 
      ch &= (ch - 1); 
      i++; 
    } 
    return i; 
} 

int main(int argc, char **argv)
{ 
	printf("%d\n", countCharBits('a'));
	printf("%d\n", countCharBits('z'));
     
    return 0; 
}   
 

/*
run:
 
3
5
 
*/

 



answered Jan 16, 2019 by avibootz

Related questions

1 answer 111 views
1 answer 77 views
1 answer 86 views
1 answer 188 views
1 answer 98 views
1 answer 179 views
179 views asked May 8, 2019 by avibootz
...