Friday, 20 December 2013

Input any positive decimal number less than 32,000 at the keyboard and convert it to its binary value for storage in a register (you can use your code from assignment 4 for this). Now add 1 to the stored number, and output the result to the console as a decimal number (i.e. the inverse of assignment 4).

    .ORIG x3000
    AND R2 R2 #0        ; counter
    AND R5 R5 #0
Input
    TRAP x20
    ADD R1 R0 #-10
    BRz InDone

    TRAP x21
    ADD R2 R2 #1
    LD R1 FE
    ADD R0 R0 R1        ; minus 48
    ADD R3 R5 #0
    AND R5 R5 #0
Loop
    ADD R3 R3 #-1
    BRn Skip
    ADD R5 R5 #10
    BR Loop
Skip
    ADD R5 R5 R0
    BR Input
InDone
    LD R3 Max
    NOT R1 R5
    ADD R1 R1 #1
    ADD R1 R3 R1
    BRnz Invalid
   
    ADD R5 R5 #1        ; valid input


    AND R0 R0 #0
    ADD R0 R0 #10
    TRAP x21
Print
    ADD R2 R2 #-1
    BRn Done
    JSR CountPower
    JSR Divide
    BR Print
Invalid                ; invalid input
    AND R0 R0 #0
    ADD R0 R0 #10
    TRAP x21
    LEA R0 ErrMsg
    TRAP x22
Done
    HALT

CountPower
    AND R4 R4 #0        ; R4 will contain n power of 10
    AND R0 R0 #0
   
    ADD R0 R0 #10
    ADD R6 R2 #0
Again
    ADD R6 R6 #-1        ; decrement counter
    BRnz Over
    AND R1 R1 #0
    ADD R1 R1 #10        ; counter for 10 to 1
Loop2
    ADD R4 R4 R0
    ADD R1 R1 #-1
    BRp Loop2

    ADD R0 R4 #0
    AND R4 R4 #0
    BR Again
Over
    ADD R4 R0 #0
    RET

Divide
    add r6 r7 #0        ; backup r7
    ADD R2 R2 #0
    BRz R2Zero
    AND R0 R0 #0
    NOT R1 R4
    ADD R1 R1 #1        ; negate 10 to power answer
Loop3
    ADD R5 R5 R1
    BRn Skip3
    ADD R0 R0 #1
    BR Loop3
R2Zero
    ADD R0 R5 #0
Skip3
    ADD R5 R5 R4
    LD R3 FE
    NOT R3 R3
    ADD R3 R3 #1        ; convert -48 to 48
    ADD R0 R0 R3
    TRAP x21
    add r7 r6 #0        ; reload r7
    RET

Max    .FILL #32000
FE    .FILL #-48
ErrMsg    .STRINGZ "Outof Range, Input should be less than 32000"
    .END

No comments:

Post a Comment