使用 "bitwise and" 运算符 c++

using "bitwise and" operator c++

我有以下代码

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
}

当我们对数字使用按位和 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++ 像这样处理按位是有原因的吗?我的猜测是它与编译器有关吗?

When we use bitwise and 1 (& 1) with a number we get back the same number.

不,我们没有。我们取回的是原数和1都设置的位组成的数,由于只设置了1的最低位,所以结果是原数的最低位。

Now my question is how does c++ evaluates the following expression: n & 1.

如果n为50,则二进制:

n:    110010
1:    000001
n&1:  000000 // no bits set in both

如果n为51,则二进制:

n:    110011
1:    000001
n&1:  000001 // one bit set in both

来自Wikipedia:

The bitwise AND operator is a single ampersand: &. It is just a representation of AND which does its work on the bits of the operands rather than the truth value of the operands. Bitwise binary AND does the logical AND (as shown in the table above) of the bits in each position of a number in its binary form.

在你的例子中110010 & 11被认为是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,我们得到一个偶数。