Friday, 20 December 2013

use the stack to build a single-digit RPN (Reverse Polish Notation) multiplier: this is a very useful method of calculation in which the operands are pushed onto the stack first, followed by the operation to be performed on them. So 12 + 17 would be entered as (12 17 +), and return 29 to the top of the stack. Start by asking the user to input two single-digit numbers separated by cr/lf (ASCII x0A), convert the ASCII input to binary, and push the two numbers onto the stack. Then call the subroutine MULTIPLY, which pops the two numbers off the stack, multiplies them, and pushes the result back onto the stack. Finally, after returning from the subroutine, pop the result off the stack, convert it to ASCII & output it to the monitor (remember that the result may be a 2 digit decimal number: you will need to use the conversion routine built in previous exercises & assignments).

    .ORIG x3000
    LD R2 StackSize
    LEA R3 Stack
    ADD R3 R3 #2
    LD R1 Minus48
    AND R4 R4 #0    ; will contain ans
Input
    TRAP x23
    ADD R0 R0 R1
    STR R0 R3 #0
    ADD R3 R3 #-1
    ADD R2 R2 #-1
    BRp Input

    LEA R3 Stack
    LDR R5 R3 #0    ; read operator
    LDR R2 R3 #1    ; reload n2 in R2
    LDR R3 R3 #2    ; reload n1 in R3

    LD R1 Plus
    ADD R1 R5 #5
    BRz Addition

    LD R1 Minus
    ADD R1 R5 #3
    BRz Subtraction

    LD R1 Mul
    ADD R1 R5 #6
    BRz Multiply

    LD R1 Div
    ADD R1 R5 #1   
    BRz Divide

    LEA R0 ErrMsg
    TRAP x22
    HALT

Print
    AND R3 R3 #0
PrintLoop
    ADD R4 R4 #-10
    BRn Skip
    ADD R3 R3 #1
    BR PrintLoop
Skip
    ADD R0 R3 #0
    LD R1 Plus48
    ADD R0 R0 R1
    TRAP x21
    ADD R4 R4 #10
    ADD R0 R4 #0
    LD R1 Plus48
    ADD R0 R0 R1
    TRAP x21
; printing done    
    HALT
Multiply
    JSR PrintNL
    LEA R0 MulMsg
    TRAP x22
Loop
    ADD R3 R3 #-1
    BRn Skip2
    ADD R4 R4 R2
    BR Loop
Skip2
    BR Print
Divide
    JSR PrintNL
    LEA R0 DivMsg
    TRAP x22
    NOT R2 R2 ADD R2 R2 #1
Loop2
    ADD R3 R3 R2
    BRn Skip2
    ADD R4 R4 #1
    BR Loop2
Skip3
    BR Print
Addition
    JSR PrintNL
    LEA R0 PlusMsg
    TRAP x22
    ADD R4 R3 R2
    BR Print
Subtraction
    JSR PrintNL
    LEA R0 MinusMsg
    TRAP x22
    NOT R2 R2     ADD R2 R2 #1
    ADD R4 R3 R2
    BRn Negative
    BR Print
Negative
    LD R0 Minus
    TRAP x21
    NOT R2 R2     ADD R2 R2 #1
    NOT R3 R3     ADD R3 R3 #1
    ADD R4 R2 R3
    BR Print
PrintNL
    ADD r5 r7 #0
    AND R0 R0 #0
    ADD R0 R0 #10
    add r7 r5 #0
    RET

Stack    .BLKW #3
StackSize    .FILL #3
Plus48    .FILL #48
Minus48    .FILL #-48

Minus    .FILL #45
Plus    .FILL #768
Mul    .FILL #42
Div    .FILL #47

PlusMsg    .STRINGZ "Addition: ";
MinusMsg    .STRINGZ "Subtraction: ";
MulMsg    .STRINGZ "Multiplication: ";
DivMsg    .STRINGZ "Division: ";
ErrMsg    .STRINGZ "Invalid Operator"
    .END

No comments:

Post a Comment