hweight.c 896 B

1234567891011121314151617181920212223242526272829303132
  1. #include <linux/bitops.h>
  2. /**
  3. * hweightN - returns the hamming weight of a N-bit word
  4. * @x: the word to weigh
  5. *
  6. * The Hamming Weight of a number is the total number of bits set in it.
  7. */
  8. unsigned int hweight32(unsigned int w)
  9. {
  10. unsigned int res = w - ((w >> 1) & 0x55555555);
  11. res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
  12. res = (res + (res >> 4)) & 0x0F0F0F0F;
  13. res = res + (res >> 8);
  14. return (res + (res >> 16)) & 0x000000FF;
  15. }
  16. unsigned long hweight64(__u64 w)
  17. {
  18. #if BITS_PER_LONG == 32
  19. return hweight32((unsigned int)(w >> 32)) + hweight32((unsigned int)w);
  20. #elif BITS_PER_LONG == 64
  21. __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
  22. res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
  23. res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
  24. res = res + (res >> 8);
  25. res = res + (res >> 16);
  26. return (res + (res >> 32)) & 0x00000000000000FFul;
  27. #endif
  28. }