khalfella

ansi_c_pg48_ch02_ex09.c

Nov 2nd, 2014
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. /*
  2. * Exercise 2-9.
  3. * In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit
  4. * in x. Explain why. Use this observation to write a faster version of
  5. * bitcount.
  6. */
  7.  
  8.  
  9. #include <stdio.h>
  10.  
  11.  
  12. /*
  13. * In a two's complement numbering system x &= (x - 1) unsets the right most 1
  14. * bit to zero. This can be explained in two setps
  15. *
  16. * a- (x - 1) unsets the right most bit and inverts all the bit in its right.
  17. * For example 8 - 1 = 7
  18. *
  19. *
  20. * __ the right most 1 bit
  21. * |
  22. * |
  23. * 8 = 0b00001000
  24. * |-|
  25. * |
  26. * - The bits in it's right
  27. *
  28. *
  29. * Unsetting the right most 1 bit and inverting the bits in its right will give
  30. * 0b00000111 = 7
  31. * b- Anding this with x will unset the right most 1 bit. That should be obvious
  32. * now :)
  33. */
  34.  
  35.  
  36. int
  37. bitcount(unsigned int x) {
  38. unsigned int ret = 0;
  39.  
  40. while (x) {
  41. x &= (x - 1);
  42. ret++;
  43. }
  44.  
  45. return ret;
  46. }
  47. int
  48. main() {
  49. unsigned int x = 14;
  50. printf ("bitcount(%X) = %d\n",x, bitcount(x));
  51. }
Advertisement
Add Comment
Please, Sign In to add comment