1 #ifndef _LINUX_BITOPS_H
2 #define _LINUX_BITOPS_H
4 #include <asm/bitops.h>
7 * ffs: find first bit set. This is defined the same way as
8 * the libc and compiler builtin ffs routines, therefore
9 * differs in spirit from the above ffz (man ffs).
12 static inline int generic_ffs(int x)
42 * fls: find last bit set.
45 extern __inline__ int generic_fls(int x)
51 if (!(x & 0xffff0000u)) {
55 if (!(x & 0xff000000u)) {
59 if (!(x & 0xf0000000u)) {
63 if (!(x & 0xc0000000u)) {
67 if (!(x & 0x80000000u)) {
74 extern __inline__ int get_bitmask_order(unsigned int count)
79 return order; /* We could be slightly more clever with -1 here... */
83 * hweightN: returns the hamming weight (i.e. the number
84 * of bits set) of a N-bit word
87 static inline unsigned int generic_hweight32(unsigned int w)
89 unsigned int res = (w & 0x55555555) + ((w >> 1) & 0x55555555);
90 res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
91 res = (res & 0x0F0F0F0F) + ((res >> 4) & 0x0F0F0F0F);
92 res = (res & 0x00FF00FF) + ((res >> 8) & 0x00FF00FF);
93 return (res & 0x0000FFFF) + ((res >> 16) & 0x0000FFFF);
96 static inline unsigned int generic_hweight16(unsigned int w)
98 unsigned int res = (w & 0x5555) + ((w >> 1) & 0x5555);
99 res = (res & 0x3333) + ((res >> 2) & 0x3333);
100 res = (res & 0x0F0F) + ((res >> 4) & 0x0F0F);
101 return (res & 0x00FF) + ((res >> 8) & 0x00FF);
104 static inline unsigned int generic_hweight8(unsigned int w)
106 unsigned int res = (w & 0x55) + ((w >> 1) & 0x55);
107 res = (res & 0x33) + ((res >> 2) & 0x33);
108 return (res & 0x0F) + ((res >> 4) & 0x0F);
111 static inline unsigned long generic_hweight64(__u64 w)
113 #if BITS_PER_LONG < 64
114 return generic_hweight32((unsigned int)(w >> 32)) +
115 generic_hweight32((unsigned int)w);
118 res = (w & 0x5555555555555555ul) + ((w >> 1) & 0x5555555555555555ul);
119 res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
120 res = (res & 0x0F0F0F0F0F0F0F0Ful) + ((res >> 4) & 0x0F0F0F0F0F0F0F0Ful);
121 res = (res & 0x00FF00FF00FF00FFul) + ((res >> 8) & 0x00FF00FF00FF00FFul);
122 res = (res & 0x0000FFFF0000FFFFul) + ((res >> 16) & 0x0000FFFF0000FFFFul);
123 return (res & 0x00000000FFFFFFFFul) + ((res >> 32) & 0x00000000FFFFFFFFul);
127 static inline unsigned long hweight_long(unsigned long w)
129 return sizeof(w) == 4 ? generic_hweight32(w) : generic_hweight64(w);