David Veloso
David Veloso

Reputation: 33

How does Lc3 division work

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.

Upvotes: 1

Views: 14242

Answers (2)

aqua
aqua

Reputation: 647

Let's take an example: 23/8, which we expect to return 2 remainder 7.

Set NUM=23 and DIVISOR=8, initializing DIVIDEND=0 and REMAINDER=0
Loop as long as NUM > DIVISOR:
   NUM = NUM - DIVISOR decreases the overall number
   DIVIDEND = DIVIDEND + 1 because we've discovered that it fits once more

At the end, REMAINDER = NUM because that's the number that could no longer have another DIVISOR subtracted from it when the loop terminates

So, let's walk through this an iteration at a time:

0) NUM=23, DIVIDEND=0
1) (23 > 8, continue) NUM=23-8=15, DIVIDEND=0+1=1
2) (15 > 8, continue) NUM=15-8=7, DIVIDEND=1+1=2
3) (8 < 7, stop)

Final answers, REMAINDER=NUM=7, DIVIDEND=2

Upvotes: 1

Chris M
Chris M

Reputation: 651

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

Upvotes: 1

Related Questions