hweight.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. 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. EXPORT_SYMBOL(__sw_hweight32);
  26. unsigned int __sw_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(__sw_hweight16);
  34. unsigned int __sw_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(__sw_hweight8);
  41. unsigned long __sw_hweight64(__u64 w)
  42. {
  43. #if BITS_PER_LONG == 32
  44. return __sw_hweight32((unsigned int)(w >> 32)) +
  45. __sw_hweight32((unsigned int)w);
  46. #elif BITS_PER_LONG == 64
  47. #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
  48. w -= (w >> 1) & 0x5555555555555555ul;
  49. w = (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
  50. w = (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
  51. return (w * 0x0101010101010101ul) >> 56;
  52. #else
  53. __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
  54. res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
  55. res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
  56. res = res + (res >> 8);
  57. res = res + (res >> 16);
  58. return (res + (res >> 32)) & 0x00000000000000FFul;
  59. #endif
  60. #endif
  61. }
  62. EXPORT_SYMBOL(__sw_hweight64);