How does Lc3 division work

David Veloso picture David Veloso · Dec 16, 2015 · Viewed 8.7k times · Source

Ive been trying to figure out how the division by subtraction works but there are no resources online that make it clear. Also i need a good example of how subroutines should look like in terms of syntax.

Answer

Chris M picture Chris M · Dec 18, 2015

There are two ways you can approach division in LC3. If you're looking for an example on how to do division through subtraction take a look at this post:

How do i do a bitshift right in binary

But if you don't have to use the subtraction method, I would recommend doing 15 bit-shifts to the left. It's more efficient because it requires less run time, and its speed isn't impacted by the number we want to bit shift.


The code below shows you how to preform a bit-shift right by using 15 bit shifts to the left:

.ORIG x3000
LD R0, VALUE

SHIFT_RIGHT
    AND R2, R2, #0              ; Clear R2, used as the loop counter

    SR_LOOP
        ADD R3, R2, #-15        ; check to see how many times we've looped
        BRzp SR_END             ; If R2 - 15 = 0 then exit

        LD R3, BIT_15           ; load BIT_15 into R3
        AND R3, R3, R0          ; check to see if we'll have a carry
        BRz #3                  ; If no carry, skip the next 3 lines
        ADD R0, R0, R0          ; bit shift left once
        ADD R0, R0, #1          ; add 1 for the carry
        BRnzp #1                ; skip the next line of code
        ADD R0, R0, R0          ; bit shift left

        ADD R2, R2, #1          ; increment our loop counter
        BRnzp SR_LOOP           ; start the loop over again
    SR_END

    ST R0, ANSWER               ; we've finished looping 15 times, store R0
    HALT

BIT_15      .FILL   b1000000000000000
VALUE       .FILL   x3BBC       ; some random number we want to bit shift right
ANSWER      .BLKW   1

.END