hweight.c 1.8 KB

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