hweight.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // SPDX-License-Identifier: GPL-2.0
  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 __sw_hweight32(unsigned int w)
  11. {
  12. #ifdef CONFIG_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. unsigned int __sw_hweight16(unsigned int w)
  26. {
  27. unsigned int res = w - ((w >> 1) & 0x5555);
  28. res = (res & 0x3333) + ((res >> 2) & 0x3333);
  29. res = (res + (res >> 4)) & 0x0F0F;
  30. return (res + (res >> 8)) & 0x00FF;
  31. }
  32. unsigned int __sw_hweight8(unsigned int w)
  33. {
  34. unsigned int res = w - ((w >> 1) & 0x55);
  35. res = (res & 0x33) + ((res >> 2) & 0x33);
  36. return (res + (res >> 4)) & 0x0F;
  37. }
  38. unsigned long __sw_hweight64(__u64 w)
  39. {
  40. #if BITS_PER_LONG == 32
  41. return __sw_hweight32((unsigned int)(w >> 32)) +
  42. __sw_hweight32((unsigned int)w);
  43. #elif BITS_PER_LONG == 64
  44. #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
  45. w -= (w >> 1) & 0x5555555555555555ul;
  46. w = (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
  47. w = (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
  48. return (w * 0x0101010101010101ul) >> 56;
  49. #else
  50. __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
  51. res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
  52. res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
  53. res = res + (res >> 8);
  54. res = res + (res >> 16);
  55. return (res + (res >> 32)) & 0x00000000000000FFul;
  56. #endif
  57. #endif
  58. }