hweight.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <linux/export.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. #ifndef __HAVE_ARCH_SW_HWEIGHT
  11. unsigned int __sw_hweight32(unsigned int w)
  12. {
  13. #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
  14. w -= (w >> 1) & 0x55555555;
  15. w = (w & 0x33333333) + ((w >> 2) & 0x33333333);
  16. w = (w + (w >> 4)) & 0x0f0f0f0f;
  17. return (w * 0x01010101) >> 24;
  18. #else
  19. unsigned int res = w - ((w >> 1) & 0x55555555);
  20. res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
  21. res = (res + (res >> 4)) & 0x0F0F0F0F;
  22. res = res + (res >> 8);
  23. return (res + (res >> 16)) & 0x000000FF;
  24. #endif
  25. }
  26. EXPORT_SYMBOL(__sw_hweight32);
  27. #endif
  28. unsigned int __sw_hweight16(unsigned int w)
  29. {
  30. unsigned int res = w - ((w >> 1) & 0x5555);
  31. res = (res & 0x3333) + ((res >> 2) & 0x3333);
  32. res = (res + (res >> 4)) & 0x0F0F;
  33. return (res + (res >> 8)) & 0x00FF;
  34. }
  35. EXPORT_SYMBOL(__sw_hweight16);
  36. unsigned int __sw_hweight8(unsigned int w)
  37. {
  38. unsigned int res = w - ((w >> 1) & 0x55);
  39. res = (res & 0x33) + ((res >> 2) & 0x33);
  40. return (res + (res >> 4)) & 0x0F;
  41. }
  42. EXPORT_SYMBOL(__sw_hweight8);
  43. #ifndef __HAVE_ARCH_SW_HWEIGHT
  44. unsigned long __sw_hweight64(__u64 w)
  45. {
  46. #if BITS_PER_LONG == 32
  47. return __sw_hweight32((unsigned int)(w >> 32)) +
  48. __sw_hweight32((unsigned int)w);
  49. #elif BITS_PER_LONG == 64
  50. #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
  51. w -= (w >> 1) & 0x5555555555555555ul;
  52. w = (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
  53. w = (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
  54. return (w * 0x0101010101010101ul) >> 56;
  55. #else
  56. __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
  57. res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
  58. res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
  59. res = res + (res >> 8);
  60. res = res + (res >> 16);
  61. return (res + (res >> 32)) & 0x00000000000000FFul;
  62. #endif
  63. #endif
  64. }
  65. EXPORT_SYMBOL(__sw_hweight64);
  66. #endif