Finding odd/even numbers with JavaScript Bitwise Operators
I wanted to share another technique for determining if a number is odd/even in JavaScript - or any other programming language. The common solution to this problem is to use the modulus (%
) operator:
With the modulus operator it's as simple as:
var isOdd = number % 2;
var isEven = !(number % 2);
However, you can achieve the same result by using the bitwise operators and ANDing the number with 1
.
var isOdd = number & 1;
var isEven = !(number & 1);
Both produce the same result, but the bitwise approach will be faster if you care about micro-optimisations.
How does this work?
When you AND two numbers together the operation returns 1
if the matching bits from both operands are 1
.
So let's take a simple example, is the decimal number 10
odd?
First convert the decimal number to binary: 0000 1010
. Now let's AND that number with decimal 1
, which is 0000 0001
when converted to binary.
0000 1010 // decimal 10
AND 0000 0001 // decimal 1
= 0000 0000
If the AND operation produces 0
the number is even - as in the previous example.
Let's look at another example using an odd decimal number:
0000 1011 // decimal 11
AND 0000 0001 // decimal 1
= 0000 0001
If the AND operation produces 1
the number is odd - as in the previous example.
Conclusion
Admittedly this isn't revolutionary, but it's good to understand how to use Bitwise operators and what type of problems they can solve.