移位运算符如何在查找两个整数中的不同位数?

How shifting operator works in finding number of different bit in two integer?

本文关键字:整数 两个 运算符 查找      更新时间:2023-10-16

我试图找出两个数字中不同位的数量。 我在这里找到了一个解决方案,但无法理解它是如何 works.it 随着和做和1正确移动的。 其实背后发生了什么?为什么要循环穿越32

void solve(int A, int B) 
{ 
int count = 0; 
// since, the numbers are less than 2^31 
// run the loop from '0' to '31' only 
for (int i = 0; i < 32; i++) { 
// right shift both the numbers by 'i' and 
// check if the bit at the 0th position is different 
if (((A >> i) & 1) != ((B >> i) & 1)) { 
count++; 
} 
} 
cout << "Number of different bits : " << count << endl; 
}

循环从 0 到 31(不是到 32(运行,因为这些是构成 32 位整数的所有可能位,我们需要检查它们。

在循环中,代码

if (((A >> i) & 1) != ((B >> i) & 1)) { 
count++; 
} 

工作原理是将两个整数中的每一个向右移动i(如果i > 0则切断位(,在移位后提取最右边的位(& 1(并检查它们是否相同(即都是 0 或两个 1(。

让我们通过一个例子:solve(243, 2182).在二进制中:

243 =                              11110011
2182 =                         100010000110
diff bits =                    ^    ^^^ ^ ^
int bits = 00000000000000000000000000000000
i =       31                              0 
<-- loop direction

产生差异的i指数为 0、2、4、5、6 和 11(我们从右到左检查 - 在第一次迭代中,i = 0,没有任何偏移,所以& 1给了我们最右边的位,等等(。在上面的示例中,每个数字左侧的填充都是 0。

另外,请注意,有更好的方法可以在没有循环的情况下做到这一点:获取两个数字的 XOR 并对它们运行popcount(计算设置的位数(:

__builtin_popcount(243 ^ 2182); // => 6

或者,更便携:

std::bitset<CHAR_BIT * sizeof(int)>(243 ^ 2182).count()

另一个注意事项:最好避免using namespace std;,返回一个值而不是产生打印副作用,并为该方法提供一个比solve更清晰的名称,例如bit_diff(我意识到这是来自极客forgeeks(。