popcount.c 798 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. static __attribute__((pure)) int popcount(int v)
  4. {
  5. if (__builtin_expect ( v != 0, 1)) {
  6. int c = 0;
  7. while (v) {
  8. if (v & 1)
  9. ++c;
  10. v>>=1;
  11. }
  12. return c;
  13. }
  14. return 0;
  15. }
  16. static __attribute__((pure)) int ctz(int v)
  17. {
  18. if (__builtin_expect ( v != 0, 1)) {
  19. int c = 0;
  20. while (1) {
  21. if((v & 1))
  22. break;
  23. ++c;
  24. v>>=1;
  25. }
  26. return c;
  27. }
  28. return sizeof v * 8;
  29. }
  30. #define TEST(f0, f1, x) { int r0 = f0(x); int r1=f1(x); \
  31. printf("[%-3s] C ==> %d vs ASM ==> %d.\n", (r0==r1) ? "OK":"BUG", r0, r1) ; }
  32. int main(int argc, char *argv[])
  33. {
  34. int v;
  35. if (argc != 2)
  36. return 1;
  37. v = strtol(argv[1], NULL, 16);
  38. printf("Pop count: ");
  39. TEST(popcount, __builtin_popcount, v)
  40. printf("CTZ : ");
  41. TEST(ctz, __builtin_ctz, v)
  42. return 0;
  43. }