8051 Program to Subtract two 8 Bit numbers

Here we will see how to subtract two 8-bit numbers using this microcontroller. The register A(Accumulator) is used as one operand in the operations. There are seven registers R0 – R7 in different register banks. We can use any of them as the second operand.

We are taking two number73H and BDH at location 20H and 21H, After subtracting the result will be stored at location 30H and 31H.

Value

.
.
.
20H
73H
21H
BDH

.
.
.
30H
00H
31H
00H

.
.
.

Program

MOVR0,#20H;set source address 20H to R0
MOVR1,#30H;set destination address 30H to R1

MOVA,@R0;take the value from source to register A
MOVR5,A; Move the value from A to R5
MOVR4,#00H; Clear register R4 to store borrow

INCR0; Point to the next location
MOVA,@R0; take the value from source to register A
MOVR3,A; store second byte
MOVA,R5;get back the first operand
SUBBA,R3; Subtract R3 from A
JNCSAVE
INCR4; Increment R4 to get borrow
MOVB,R4;Get borrow to register B
MOV@R1,B; Store the borrow first
INCR1; Increase R1 to point to the next address

SAVE:  MOV@R1,A; Store the result
HALT:  SJMP HALT ;Stop the program

So by subtracting 73H –BDH, the result will be B6H. At location 30H, we will get 01H. This indicates that the result is negative. The get the actual value from result B6H, we have to perform 2’s complement operation. After performing 2’s Complement, the result will be -4AH.

Value

.
.
.
20H
73H
21H
BDH

.
.
.
30H
01H
31H
B6H

.
.
.