hweight.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <linux/module.h>
  2. #include <asm/types.h>
  3. #include <asm/bitops.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. unsigned int res = w - ((w >> 1) & 0x55555555);
  13. res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
  14. res = (res + (res >> 4)) & 0x0F0F0F0F;
  15. res = res + (res >> 8);
  16. return (res + (res >> 16)) & 0x000000FF;
  17. }
  18. EXPORT_SYMBOL(hweight32);
  19. unsigned int hweight16(unsigned int w)
  20. {
  21. unsigned int res = w - ((w >> 1) & 0x5555);
  22. res = (res & 0x3333) + ((res >> 2) & 0x3333);
  23. res = (res + (res >> 4)) & 0x0F0F;
  24. return (res + (res >> 8)) & 0x00FF;
  25. }
  26. EXPORT_SYMBOL(hweight16);
  27. unsigned int hweight8(unsigned int w)
  28. {
  29. unsigned int res = w - ((w >> 1) & 0x55);
  30. res = (res & 0x33) + ((res >> 2) & 0x33);
  31. return (res + (res >> 4)) & 0x0F;
  32. }
  33. EXPORT_SYMBOL(hweight8);
  34. unsigned long hweight64(__u64 w)
  35. {
  36. #if BITS_PER_LONG == 32
  37. return hweight32((unsigned int)(w >> 32)) + hweight32((unsigned int)w);
  38. #elif BITS_PER_LONG == 64
  39. #ifdef ARCH_HAS_FAST_MULTIPLIER
  40. w -= (w >> 1) & 0x5555555555555555ul;
  41. w = (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
  42. w = (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
  43. return (w * 0x0101010101010101ul) >> 56;
  44. #else
  45. __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
  46. res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
  47. res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
  48. res = res + (res >> 8);
  49. res = res + (res >> 16);
  50. return (res + (res >> 32)) & 0x00000000000000FFul;
  51. #endif
  52. #endif
  53. }
  54. EXPORT_SYMBOL(hweight64);