Basically if I had a number in D1, and wanted it to ALWAYS be even, how would I make sure it is never odd?
I know it has something to do with the AND instruction. But when I tried that, it would always subtract 1. So it would turn odd numbers even and even numbers odd.
How can I basically do if n is odd, sub 1
and
your number with -2
.
In 2's complement representation -2 is a number with all bits set to one except the lowest one (11111...110), so, used as a mask, it always kills just the low bit of your number. This forces it to be even (it works correctly even for negative numbers).
As for the "viceversa" in the title: to do the opposite (=force every even number to the next odd), just or
with 1
. This sets the low bit to be 1, which obtains the required effect.
Odd numbers end with 1
in binary, and even numbers end with 0
in binary. What you really want is to make the last binary digit be 0
, regardless of what it started as. (That'll subtract 1 from odd numbers, and leave even numbers unchanged.)
The way to do this is to AND with 1111...1110
, where all binary digits are 1
except the last digit, which is 0
. You can construct this by doing a bitwise negation on 0000...0001
, which of course is just 1
.
So if your number is n
, you want to compute n & (~1)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With