__fls 源码分析

来源:互联网 发布:淘宝店铺怎么加入淘客 编辑:程序博客网 时间:2024/05/29 12:37

__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
0 0