bitops.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef _LINUX_BITOPS_H
  2. #define _LINUX_BITOPS_H
  3. /*
  4. * ffs: find first bit set. This is defined the same way as
  5. * the libc and compiler builtin ffs routines, therefore
  6. * differs in spirit from the above ffz (man ffs).
  7. */
  8. static inline int generic_ffs(int x)
  9. {
  10. int r = 1;
  11. if (!x)
  12. return 0;
  13. if (!(x & 0xffff)) {
  14. x >>= 16;
  15. r += 16;
  16. }
  17. if (!(x & 0xff)) {
  18. x >>= 8;
  19. r += 8;
  20. }
  21. if (!(x & 0xf)) {
  22. x >>= 4;
  23. r += 4;
  24. }
  25. if (!(x & 3)) {
  26. x >>= 2;
  27. r += 2;
  28. }
  29. if (!(x & 1)) {
  30. x >>= 1;
  31. r += 1;
  32. }
  33. return r;
  34. }
  35. /*
  36. * hweightN: returns the hamming weight (i.e. the number
  37. * of bits set) of a N-bit word
  38. */
  39. static inline unsigned int generic_hweight32(unsigned int w)
  40. {
  41. unsigned int res = (w & 0x55555555) + ((w >> 1) & 0x55555555);
  42. res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
  43. res = (res & 0x0F0F0F0F) + ((res >> 4) & 0x0F0F0F0F);
  44. res = (res & 0x00FF00FF) + ((res >> 8) & 0x00FF00FF);
  45. return (res & 0x0000FFFF) + ((res >> 16) & 0x0000FFFF);
  46. }
  47. static inline unsigned int generic_hweight16(unsigned int w)
  48. {
  49. unsigned int res = (w & 0x5555) + ((w >> 1) & 0x5555);
  50. res = (res & 0x3333) + ((res >> 2) & 0x3333);
  51. res = (res & 0x0F0F) + ((res >> 4) & 0x0F0F);
  52. return (res & 0x00FF) + ((res >> 8) & 0x00FF);
  53. }
  54. static inline unsigned int generic_hweight8(unsigned int w)
  55. {
  56. unsigned int res = (w & 0x55) + ((w >> 1) & 0x55);
  57. res = (res & 0x33) + ((res >> 2) & 0x33);
  58. return (res & 0x0F) + ((res >> 4) & 0x0F);
  59. }
  60. #include <asm/bitops.h>
  61. #endif