hweight.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <linux/bitops.h>
  2. #include <asm/types.h>
  3. /**
  4. * hweightN - returns the hamming weight of a N-bit word
  5. * @x: the word to weigh
  6. *
  7. * The Hamming Weight of a number is the total number of bits set in it.
  8. */
  9. unsigned int __sw_hweight32(unsigned int w)
  10. {
  11. #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
  12. w -= (w >> 1) & 0x55555555;
  13. w = (w & 0x33333333) + ((w >> 2) & 0x33333333);
  14. w = (w + (w >> 4)) & 0x0f0f0f0f;
  15. return (w * 0x01010101) >> 24;
  16. #else
  17. unsigned int res = w - ((w >> 1) & 0x55555555);
  18. res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
  19. res = (res + (res >> 4)) & 0x0F0F0F0F;
  20. res = res + (res >> 8);
  21. return (res + (res >> 16)) & 0x000000FF;
  22. #endif
  23. }
  24. unsigned int __sw_hweight16(unsigned int w)
  25. {
  26. unsigned int res = w - ((w >> 1) & 0x5555);
  27. res = (res & 0x3333) + ((res >> 2) & 0x3333);
  28. res = (res + (res >> 4)) & 0x0F0F;
  29. return (res + (res >> 8)) & 0x00FF;
  30. }
  31. unsigned int __sw_hweight8(unsigned int w)
  32. {
  33. unsigned int res = w - ((w >> 1) & 0x55);
  34. res = (res & 0x33) + ((res >> 2) & 0x33);
  35. return (res + (res >> 4)) & 0x0F;
  36. }
  37. unsigned long __sw_hweight64(__u64 w)
  38. {
  39. #if BITS_PER_LONG == 32
  40. return __sw_hweight32((unsigned int)(w >> 32)) +
  41. __sw_hweight32((unsigned int)w);
  42. #elif BITS_PER_LONG == 64
  43. #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
  44. w -= (w >> 1) & 0x5555555555555555ul;
  45. w = (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
  46. w = (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
  47. return (w * 0x0101010101010101ul) >> 56;
  48. #else
  49. __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
  50. res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
  51. res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
  52. res = res + (res >> 8);
  53. res = res + (res >> 16);
  54. return (res + (res >> 32)) & 0x00000000000000FFul;
  55. #endif
  56. #endif
  57. }