hweight.c 1.4 KB

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