LC-3 Assembly Subtract Two Numbers

mandy picture mandy · Feb 24, 2016 · Viewed 11.6k times · Source

I am having problem with this question as I am new to LC-3 programming.

Write a LC-3 code to subtract the value in R1 from the value in R0 and place the result in R5. That is, write the assembly code for R5 := R0 - R1. Assume R1=10 and R0 is 12.

Answer

user5398967 picture user5398967 · Feb 24, 2016

Per your question, we can assume that 12 and 10 are already in R0 and R1, so the correct algorithm starts at the NOT instruction and ends at HALT; however, the other instructions are included to allow you to run this code.

The solution is to add R0 with -R1. We find -R1 by doing bitwise inversion (NOT) on the number in R1 and adding 1. This gives us the 2's complement negation of R1.

If you do not understand two's complement arithmetic, I suggest looking here. After the subtraction in performed, we restore the original number to R1.

.orig x3000

LD R0, A        ; A(12) => R0 (this is assumed)
LD R1, B        ; B(10) => R1 (this is assumed)
                ; find negative of the two's complement number in R1
NOT R1, R1
ADD R1, R1, 1
ADD R5, R0, R1  ; R0 - R1 => R5
LD R1, B        ; Restore R1
HALT

A .fill 12
B .fill 10

.end