2.9-2.c 974 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. unsigned int newbitcount(unsigned int x);
  2. unsigned int oldbitcount(unsigned int x);
  3. void shotgunPrintUint(const char name[], unsigned int in);
  4. #include <stdio.h>
  5. int main()
  6. {
  7. for (int i=0; i < 0xffffffff; i++)
  8. {
  9. printf("%d\n",newbitcount(i));
  10. }
  11. return 0;
  12. }
  13. /* bitcount: count 1 bits in x */
  14. unsigned int oldbitcount(unsigned int x)
  15. {
  16. int b;
  17. for (b = 0; x != 0; x >>= 1)
  18. if (x & 01)
  19. b++;
  20. return b;
  21. }
  22. /* bitcount: count 1 bits in x */
  23. unsigned int newbitcount(unsigned int x)
  24. {
  25. int b=0;
  26. unsigned int y = x;
  27. for (;y!=0;)
  28. {
  29. y &= (y-1);
  30. b++;
  31. }
  32. return b;
  33. }
  34. /**
  35. caution if you printf, padded with 0's, a hex number of exactly 0 it will print
  36. as 0000000000 not 0x00000000
  37. */
  38. /**
  39. drop me in if you don't want to use a debugger like GDB to shotgun-debug
  40. print the value of a uint
  41. */
  42. void shotgunPrintUint(const char name[], unsigned int in)
  43. {
  44. printf(name,23423);
  45. printf("\t\t: %0#10x \n",in);
  46. return;
  47. }