I saw some very neat usage of '&' like:
int k;
int result=(k&2);
another example is:
int k;
int result=(k&1);
Can anyone explain to me how '&' works?
I tried to use cout<< to figure it out. For (k&2), result=0 when k=0, or k=1. If k>=2, it returns 2.
For (k&1), seems like when k is an odd number, it returns 1, otherwise, it returns 0.
Is that about right? Would you please give me more examples, so I can learn this trick.
Thank you
hfl
The bitwise-AND operator (&) compares each bit of its first operand to the corresponding bit of its second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
In the following example, the bitwise-AND operator (&) compares the bits of two integers, nNumA and nNumB:
// Example of the bitwise-AND operator
int nNumA=1, nNumB=3, nNumC; // 00000001, 00000011
nNumC = nNumA & nNumB; // nNumC is now 00000001