fork download
  1. #include <stdio.h>
  2. #include <memory.h>
  3.  
  4. void printb(unsigned int x);
  5. int bitcount(unsigned x);
  6. int bitcount2(unsigned x);
  7.  
  8.  
  9. int main(void){
  10. int i;
  11. unsigned int x = 0xFF30;
  12.  
  13. printb(x);
  14. printf("%d\n", bitcount(x));
  15. printf("%d\n", bitcount2(x));
  16.  
  17.  
  18. return 0;
  19. }
  20.  
  21. int bitcount(unsigned x){
  22. int b;
  23.  
  24. for(b = 0; x != 0; x >>= 1)
  25. if(x&1)
  26. b++;
  27. return b;
  28. }
  29.  
  30. int bitcount2(unsigned x){
  31. int b = 0;
  32.  
  33. while(x > 0)
  34. if(x &= (x-1))
  35. b++;
  36. return b;
  37. }
  38.  
  39. void printb(unsigned int x){
  40. int i;
  41. int mask = 0x1;
  42.  
  43. for(i = 15; i >= 0; i--){
  44. printf("%d", (x >> i) & mask);
  45. if((i % 4) == 0) putchar(' ');
  46. }
  47. putchar('\n');
  48. }
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
1111 1111 0011 0000 
10
9