Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn an odd number even, or vice versa, in Motorola 68000 Assembly?

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

like image 678
Josh Jeabos Avatar asked Dec 08 '22 14:12

Josh Jeabos


2 Answers

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.

like image 139
Matteo Italia Avatar answered Mar 08 '23 23:03

Matteo Italia


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).

like image 36
k_ssb Avatar answered Mar 09 '23 00:03

k_ssb