8051 code to find a number is even or odd
So the basic logic we use is to check weather a number divides with 2 or not . Here we can use another logic by rotating the value in the accumulator to the right through carry and then make the decision based on the value of the carry.I will post both the methods..
Method 1: Using DIV instruction
ORG 000h
MOV A,#number ;The number to be checked for even or odd
MOV B,#02h ;divisor
DIV AB ;Divides the unsigned value of the Accumulator by the unsigned value of the "B" register. The resulting quotient is placed in the Accumulator and the remainder is placed in the "B" register.If remainder is 1 then the number is odd.
MOV R0,B
CJNE R0,#0h,odd
MOV A,#00h ; moving 0 to show its even
SJMP even
odd: MOV A,#01h ;moving 1 to accumulator to show the number is odd...you can do any other operation.
even: NOP
END
Now why did i add "SJMP even " is the code executes sequentially ,even there is a label .The compiler does not skip labels.
METHOD 2: Using RR instruction
ORG 000h
MOV A,#number ;The number to be checked for even or odd
RRC A ;rotates the accumulator right through carry
JC odd
MOV A,#00h ; moving 0 to show its even
SJMP even
odd: MOV A,#01h ;moving 1 to accumulator to show the number is odd...you can do any other operation.
even: NOP
END
If the number is odd the it will have the lsb as binary 1,and if even lsb will be binary 0....
No comments: