TIL: bitwise & to check odd number
published
last modified
3kb
We can use the bitwise operator &
to check if an integer is odd. Bitwise operators operate on element wise on bits. You can think of it has checking:
Are both bits 1?
Example
If we take the example above and &
it we get:
as only the 5th element had both 1s.
What Does This Have to Do with Even and Odd Numbers?
We can use this operator to check if an integer is odd. We do this by &
any integer with 1.
The idea is if the least significant bit (the right most bit) is 'on' (equal to 1) then we are just adding one to powers of two which is odd. Otherwise it's even.
Odd
For example the number 17 in binary is:
If we &
this with one:
We get a 1
, meaning it is odd.
Even
Contrast that with 12. We get 0
, which means the number is even.
Next time you want to check even and odd numbers, this may be a quicker way then using n % 2 == 0
. Or better yet just run the code below and see for yourself.
Results
On one of the runs on my Macbook Pro M1:

100 iterations testing even with bits: $0.0006432533264160156s$

100 iterations testing even with mod: $0.0687568187713623s$
Pretty nifty I think.
Contact
If you have any comments or thoughts you can reach me at any of the places below.