What does (i & 1) do?

I'm trying to understand what the below code is actually doing? I thought (i & 1) would display odd numbers and (i & 2) would display even numbers. But (i & 2) gives me another odd answer. What does this actually do?

Output for the below code is:
(i & 1) = 1,3,5,7,9
(i & 2) = 2,3,6,7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 #include <iostream>

using namespace std;

int main()
{
    for (int i = 0; i < 10 ; i++)
    {
        if (i & 1)
        {
            cout << i << endl;
        }
    }
}
The '&' operator is the bitwise AND operator. It is used to compare bits with each other in the AND operation. Here is more info on it:

http://www.cprogramming.com/tutorial/bitwise_operators.html
Of course.. I clean forgot about that. So the 1 acts as a bitmask for i .
Can't believe I didn't see that.

Thanks.
i&2 would not display even numbers. You should use i&0 instead.
@hatsack:


i&0 is always 0. It wouldn't print anything.
Topic archived. No new replies allowed.