using bitwise and operator c++
我有以下代码
1 2 3 4 5 6 | 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&AMP;1。因为:
1 2 3 4 5 6 7 | 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++有这样的理由来处理位和像这样吗?我猜这和编译器有关吗?
维基百科:
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.
在您的示例中,
1 2 3 4 | if(1 & num) printf("it is odd"); else printf("it is even"); |
这就是它的工作原理:假设您有一个8位的数字。现在,
如果我现在对每一位执行
我号码的最后一位是什么时候?那什么时候呢?当转换为十进制形式时,最后一位乘以20。并且,20=1。如果这个
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.
如果
1 2 3 | n: 110010 1: 000001 n&1: 000000 // no bits set in both |
如果
1 2 3 | n: 110011 1: 000001 n&1: 000001 // one bit set in both |