【宏定义】——判断一个整数是不是 2 的幂

基本思路

f = v & (v - 1) == 0;

这种方式 0 是不对的,改进之后

f = v && !(v & (v - 1));

代码实现

#include <stdio.h>

#define is_power(v)         ((v) && !((v) & ((v) - 1)))

int main(int argc, char *argv[])
{
    
    
   printf("%d\n", is_power(0));
   printf("%d\n", is_power(1));
   printf("%d\n", is_power(2));
   printf("%d\n", is_power(3));
   printf("%d\n", is_power(4));
   printf("%d\n", is_power(8));

   return 0;
}

结果

0
1
1
0
1
1

参考代码:http://graphics.stanford.edu/~seander/bithacks.html

猜你喜欢

转载自blog.csdn.net/tyustli/article/details/132328196