How does condition statement work with bit-wise operators?
Yes, you are right in the last part. Binary &
and |
are performed bit by bit. Since
1 & 1 == 1
1 & 0 == 0
0 & 1 == 0
0 & 0 == 0
we can see that:
8 & 1 == 1000 & 0001 == 0000
and
7 & 1 == 0111 & 0001 == 0001
Your test
function does correctly compute whether a number is even or odd though, because a & 1
tests whether there is a 1
in the 1s place, which there only is for odd numbers.
Actually, in C, C++ and other major programming languages the &
operator do AND
operations in each bit for integral types. The nth bit in a bitwise AND
is equal to 1 if and only if the nth bit of both operands are equal to 1.
For example:
8 & 1 =
1000 - 8
0001 - 1
----
0000 - 0
7 & 1 =
0111 - 7
0001 - 1
----
0001 - 1
7 & 5 =
0111 - 7
0101 - 5
----
0101 - 5
For this reason doing a bitwise AND
between an even number and 1
will always be equal 0
because only odd numbers have their least significant bit equal to 1
.
if(x)
in C++ converts x
to boolean. An integer is considered true
iff it is nonzero.
Thus, all if(i & 1)
is doing is checking to see if the least-significant bit is set in i
. If it is set, i&1
will be nonzero; if it is not set, i&1
will be zero.
The least significant bit is set in an integer iff that integer is odd, so thus i&1
is nonzero iff i
is odd.