I came across this piece of code on reddit
1 - ((num & 1) << 1) as i32
This code returns 1 for even numbers and -1 for odd numbers.
It takes less instructions than other ways of calculating the same thing, and is presumably, quite fast. So, how does it work? (A step-by-step breakdown would be helpful)
Note: I found What is the fastest way to find if a number is even or odd?, but don't understand how that works either.
Let's break this down from the inside out.
num & 1This "masks" all but the least significant bit using a bitwise and. Since the least significant bit is the "ones" place, it will evaluate to
1if the number is odd or0if the number is even.(result1) << 1This bitshifts that left by 1. This has the effect of multiplying by two. If
numwas odd, this will evaluate to2or still0ifnumwas even. (0 * 2 = 0)(result2) as i32This casts the resulting unsigned integer (
2or0) into a signed integer, allowing us to subtract it in the next operation. This is only for the compiler, it has no effect on the value in memory.1 - result3This subtracts the previous number from
1. Ifnumwas even, we get1 - 0which results in a final answer of1. Ifnumwas odd, we get1 - 2which results in a final answer of-1.