现在的位置: 首页 > 综合 > 正文

内核当中的test_bit宏

2014年12月10日 ⁄ 综合 ⁄ 共 1804字 ⁄ 字号 评论关闭


 

1.对于编译时的常数使用上面的函数进行判断

假设我们要测试的数为test = 0x00000008,它的第三位是否为1(位数是从0数起),即nr = 3 = 0x00000003,addr就是我们测试的数的地址

addr = &test; 对于运算addr[nr >> 5] = addr[0] 也就是test的值

对于前面部分 1UL左移3位,其值就是0x00000008,它们&运算后,结果是0x00000008 != 0,所以return的结果返回是1

即0x00000008的第3位是1,其结果也确实是1。其他的情况照样子可以这样子验证。

 


 
2.对于编译时的非常数,使用上面的函数进行判断。上面使用了gcc的内联汇编。参数nr和addr的含义和上面相同,其实就两句,翻译成Intel格式如下:
BT
nr, (addr)                ;测试(addr)的第nr位,如果是1,则CF = 1
SUBB
oldbit, oldbit     ;带进位的减法,因为上面置CF = 1,所以结果是1
然后函数最后返回oldbit的值,也就是1了。
上面的汇编语言可以参看Intel Architecture Software Developer’s Manual

 
3.最后,test_bit其实是一个宏,看nr的属性(是否是编译时常数调用不同的函数),gcc的内建函数__builtin_constant_p(nr),测试nr是否是编译时的常量,如果是则返回1,然后调用constant_test_bit函数,否则调用variable_test_bit函数。下面是引用gcc手册的关于__builtin_constant_p(EXP)内建函数的说明。详细内容可以参看gcc的info文档。

     You can use the built-in function `__builtin_constant_p' to
     determine if a value is known to be constant at compile-time and
     hence that GCC can perform constant-folding on expressions
     involving that value.  The argument of the function is the value
     to test.  The function returns the integer 1 if the argument is
     known to be a compile-time constant and 0 if it is not known to be
     a compile-time constant.  A return of 0 does not indicate that the
     value is _not_ a constant, but merely that GCC cannot prove it is
     a constant with the specified value of the `-O' option.

 

抱歉!评论已关闭.