使用"按位与"运算符c++

人气:577 发布:2022-10-16 标签: bit-manipulation c++ bitwise-operators bit

问题描述

我有以下代码

int n = 50;
while(n) {                         //1
    if(n & 1) cout << "1" << endl; //2 
    //right shift the number so n will become 0 eventually and the loop will terminate
    n >>= 1;                       //3
}

当我们对数字使用按位AND 1(&;1)时,我们得到的是相同的数字。 现在我的问题是,c++如何计算以下表达式:N&;1。 发件人:

  n = 50
  In binary form 50 is:            110010
  If we bitwise 1 then we get:  AND     1 = 110010
  Now in c++ (2) the expression evaluates like this:
  Instead of getting the whole sequence of bits (110010) bitwise anded with 1    
  it evaluates only the number of right bits we bitwise. In my example:
  n=50, 110010, use n & 1 ==> 0 AND 1 instead of 110010 AND 1.

c++这样按位处理有什么原因吗?我的猜测是这与编译器有关?

推荐答案

来自Wikipedia:

按位AND运算符是单个与号:&;。它只是操作数比特的表示,而不是操作数的真值。按位二进制,并对二进制形式的数字的每个位置中的位进行逻辑与(如上表所示)。

在您的示例110010&;1中,1被认为是000001,然后每一位都是anded,您就得到了结果。事实上,我使用这个方法:1&number来检查偶数和奇数。方法如下:

if(1 & num)
  printf("it is odd");
else 
  printf("it is even");

它是这样工作的:假设您有一个8位数字。现在,1的8位表示法将是00000001

如果我现在对每个位执行and,对于前七个位,我将得到0,因为它将是0 & anything将是0。现在,1的最后一位是1。所以,如果我的数字的最后一位也是1,那么1 & 1 = 1,如果我的最后一位是0,那么1 & 0 = 0

我的数字中的最后一位何时为1?什么时候0?转换为小数形式时,最后一位乘以20。并且,20=1。如果这个1乘以1,我们得到一个奇数,如果它乘以0,我们得到一个偶数。

464