lolamontes69

K+R Exercise2_9

Sep 5th, 2014
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.40 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int bitcount(unsigned x);
  4.  
  5. int main()
  6. {
  7.     unsigned x;
  8.     int res;
  9.  
  10.     printf("Enter x > ");
  11.     scanf("%u",&x);
  12.     res = bitcount(x);
  13.     printf("\n1 bits in %u = %u\n",x, res);
  14.     return(0);
  15. }
  16. /* bitcount count 1 bits in x */
  17. int bitcount(unsigned x)
  18. {
  19.     int b=0;
  20.     if(x==0) return 0;       // Idiot test.
  21.     while(x&=(x-1))
  22.         ++b;
  23.     return b+1;
  24. }
Advertisement
Add Comment
Please, Sign In to add comment