__fls 用于找到一个long型数最后哪个bit为1,例如0x1010的话,__fls 就返回12,表示最高为是第12bit
源码分析如下:
static __always_inline unsigned long __fls(unsigned long word)
{
int num = BITS_PER_LONG - 1;
#if BITS_PER_LONG == 64
if (!(word & (~0ul << 32))) {
num -= 32;
word <<= 32;
}
#endif
if (!(word & (~0ul << (BITS_PER_LONG-16)))) {
num -= 16;
word <<= 16;
}
if (!(word & (~0ul << (BITS_PER_LONG-8)))) {
num -= 8;
word <<= 8;
}
if (!(word & (~0ul << (BITS_PER_LONG-4)))) {
num -= 4;
word <<= 4;
}
if (!(word & (~0ul << (BITS_PER_LONG-2)))) {
num -= 2;
word <<= 2;
}
if (!(word & (~0ul << (BITS_PER_LONG-1))))
num -= 1;
return num;
}
假定BITS_PER_LONG ==32
则~0ul ==0xFFFFFFFF
第一步:!(word & (~0ul << (BITS_PER_LONG-16))) =!(0x1010 & 0xFFFF0000)=1,则num -=16=15.word = 0x1010 0000
第二步:!(word & (~0ul << (BITS_PER_LONG-8))) =!(0x1010 & 0xFF000000)=0,则num=15.word = 0x1010 0000
第三步:!(word & (~0ul << (BITS_PER_LONG-4))) =!(0x1010 & 0xc0000000)=0,则num=15.word = 0xf0000000
第三步:!(word & (~0ul << (BITS_PER_LONG-2))) =!(0x1010 & 0xc0000000)=1,则num=13.word = 0x40400000
第四步:!(word & (~0ul << (BITS_PER_LONG-2))) =!(0x1010 & 0x80000000)=1,则num=12.word = 0x40400000
所以最终返回12