【算法笔记】C++中的二进制运算

保留 最低位的1----x & (-x)

int x  = 0b00001010;
//-x = 0b11110110

int lsb= ( x == INT_MIN ? x: x& (-x) );
// lsb(lowestSignificantBit)

>>> lsb = 0b0000 0010

去掉 最低位的1----x&(x-1)

int x = 0b00000110;
//x-1 = 0b00000101

int non_lsb = x & (x-1);

>>> non_lsb = 0b00000100

C++ 二进制 内置函数

1的个数

计算一个 32 位无符号整数有多少个位为1

int num = 9;
int cnt_one = __builtin_popcount(num);
//cnt_bit == 2;

猜你喜欢

转载自blog.csdn.net/LittleSeedling/article/details/121058205