static __always_inline unsigned long __ffs(unsigned long word)

D:\SourceCode\linux-2.6.32-220.el6\include\asm-generic\bitops\__ffs.h

/**

 * __ffs - find first bit in word.,返回word中第一个置位的位的位数(包括0)。例如:0x1,r=0;0x2,r=1;0x3,r=0;0x4,r=2.....
 * @word: The word to search
 *
 * Undefined if no bit exists, so code should check against 0 first.  //对0x0无效,代码需要检测入参不能为0,为何不在函数中检测呢?

 */

函数似乎利用了"折半查找"的方法,加快执行过程。以64位为例,每个函数都是通过6次比较即可获取到结果。

以word=0x1000,0000,0000为例,查看下函数执行过程

static __always_inline unsigned long __ffs(unsigned long word)

{
    int num = 0;

#if BITS_PER_LONG == 64

    if ((word & 0xffffffff) == 0) { //执行后num=32 word=0x1000

        num += 32;
        word >>= 32;
    }
#endif
    if ((word & 0xffff) == 0) { //跳过
        num += 16;
        word >>= 16;
    }
    if ((word & 0xff) == 0) { //执行后num=40,word=0x10
        num += 8;
        word >>= 8;
    }
    if ((word & 0xf) == 0) { //执行后num=44,word=0x1
        num += 4;
        word >>= 4;
    }
    if ((word & 0x3) == 0) { //跳过
        num += 2;
        word >>= 2;
    }
    if ((word & 0x1) == 0) //跳过
        num += 1;
    return num;                //返回值44
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值