关于C中test_bit宏的问题

cra*_*ter 3 c macros bit-manipulation

我在C中使用了以下宏:

#define   test_bit(_n,_p)     !! ( _n & ( 1u << _p))
Run Code Online (Sandbox Code Playgroud)

我已经研究了宏,但我需要确定在宏中使用双阴影,以及它与宏定义的行为有何不同:

#define   test_bit(_n,_p)     ( _n & ( 1u << _p))
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 10

想想在测试特定位时会发生什么:

  1111 1111 (0xff)
& 0000 0100 (0x04, bit 2)
  ---- ----
= 0000 0100 (0x04)
Run Code Online (Sandbox Code Playgroud)

如果你这样离开它,你的结果将是bitmask本身.

现在考虑对此的双重否定,这与什么都不做是一样的:

!4 -> 0
!0 -> 1
Run Code Online (Sandbox Code Playgroud)

换句话说,!!4给你1而不是4,这保证你将获得0/1真值而不是0/whatever-the-bitmask-was价值.


以下程序显示了此操作:

#include <stdio.h>

#define test_bit0(_n,_p)   (_n & (1u << _p))
#define test_bit1(_n,_p) !!(_n & (1u << _p))

int main (void) {
    printf ("%d %d\n", test_bit0 (0xff, 2), test_bit1 (0xff,2));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它输出:

4 1
Run Code Online (Sandbox Code Playgroud)

正如所料.

另外:现在编写代码的地方很少,因为现代编译器不仅可以自动编写代码并选择最有效的方法来执行操作((_n & (1u << _p)) != 0).并且不要让我开始使用钝变量名,使用numberposition提供更多的可读性,它在编译时丢失:-)