I have the following code
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
}
When we use bitwise and 1 (& 1) with a number we get back the same number. Now my question is how does c++ evaluates the following expression: n & 1. Since:
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.
Is there a reason that c++ treats the bitwise and like this? My guess would be it has to do with the compiler ?
From 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.
In your example 110010
& 1
, 1
is considered as 000001
, and then each bit is anded
and you get the result. In fact, I use this method: 1&number
to check for even and odd numbers. This is how:
if(1 & num)
printf("it is odd");
else
printf("it is even");
This is how it works: suppose you have an 8 bit number. Now, the 8 bit notation of 1
will be 00000001
.
If I now perform and
on each bit, for all the first seven bits I will get 0
, because it will be 0 & anything
will be 0. Now, the last bit of 1
is 1. So, if my number also has last bit as 1
, then 1 & 1 = 1
, and if my last bit is 0
, then 1 & 0 = 0
.
When will the last bit in my number be 1
? And when 0
? When converting to decimal form, the last bit is multiplied by 20. And, 20 = 1. If this 1
is multiplied with 1, we get an odd number, and if it is multiplied with 0, we get an even number.