evaluate an odd number

From a technical blog, I learned a trick to check whether i is odd number by evaluating

(i & 1) != 0

I am not sure how it works?
(i & 1) evaluates to 1 if the least significant bit of i is 1, and to 0 otherwise. The thing here is that a number is odd if-f its least significant bit is 1. Think about it...

A binary number looks like this:

... dn ... d2 d1 d0, where dk are the individual digits, each being either one or zero.

The value of this number is:

... + 2n * dn + ... + 22 * d2 + 21 * d1 + 20 * d0

As you can see, in the above sum, every term other than 20 * d0 is always even.
Thus, if d0 is 0 the number is even and if d0 is 1 the number is odd.

Last edited on
If you look at numbers in binary form you will notice that the least significant column alternates between 0 and 1. So all even numbers end in 0 and all odd numbers end in 1 in binary.


0000 = 0
0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = 8
1001 = 9
1010 = 10
1011 = 11
1100 = 12
1101 = 13
1110 = 14
1111 = 15



So the simplest wa to check if a number is odd or even is by examining the least significant bit. This is done using the bitwise AND operator &
Thanks for your explanations.
Topic archived. No new replies allowed.