Assembly Language Check for ODD / EVEN

From TRCCompSci - AQA Computer Science
Revision as of 08:13, 14 January 2019 by Admin (talk | contribs) (Assembly Version)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

A Bitwise AND can be used to test for ODD & EVEN. A Bitwise AND compares 2 binary patterns digit by digit, the output will be a 1 if both patterns are a 1 and all other combinations will be a 0.

To check for ODD we can Bitwise AND the number with 1, the binary would obviously be '00000001'. This will therefore check if the 1's place value is set in the other number. When we compare you can branch if they are equal.

To check for EVEN we repeat the above, but after we compare you can branch if not equal.

To check

C# example

int y = 20;
if (y % 2 == 0)
{
    x = 9;
}

Assembly Version

     MOV R0,#20
     MOV R1,#1
     AND R3,R0,R1
     CMP R3, R1
     BEQ end
     MOV R9,#9 
end:
     halt


Line 1 sets the value of Register 0 to the value 20 (this is the value to test).
Line 2 sets the value of Register 1 to the value 1 (this is used in the and).
Line 3 is a bitwise AND between 20 and 1, this will check if the binary value ends in a 1 (ie odd).
Line 4 compare the outcome of the AND with the value #1.
Line 5 will branch to the end label if the compare was not equal (ie it was odd).
Line 6 will be run if the compare was equal, used so we know the outcome.
Line 7 is the end label.
Line 8 is the halt.