Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does this code check for parity of a number? (even or odd)

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Let’s break this down from the inside out.

  1. num & 1

This "masks" all but the least significant bit using a bitwise and. Since the least significant bit is the "ones" place, it will evaluate to 1 if the number is odd or 0 if the number is even.

  1. (result1) << 1

This bitshifts that left by 1. This has the effect of multiplying by two. If num was odd, this will evaluate to 2 or still 0 if num was even. (0 * 2 = 0)

  1. (result2) as i32

This casts the resulting unsigned integer (2 or 0) 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. 1 - result3

This subtracts the previous number from 1. If num was even, we get 1 - 0 which results in a final answer of 1. If num was odd, we get 1 - 2 which results in a final answer of -1.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading