assemblylittle-man-computer

Little Man Computer Program to convert an n-bit binary number into a decimal number


I am working on the following challenge:

Write a LMC program that can convert an n-bit binary number into a decimal number. Display the natural number as output before halting the program. The first input determines the value for n. It is assumed this value will be equal to four, or greater. For example, if the first input is eight (8) then eight subsequent inputs are requested. If the subsequent inputs number were 1, 0, 0, 1, 0, 0, 0, 0 then the output would be 9.n input values are provided by the user, one for each bit: The first of these is the least-significant bit. The n’th input is the most-significant bit.

My attempt:

       IN
       BRZ INVALID_N
       STO N
       LDA N
       SUB FOUR
       BRP VALID_N
INVALID_N:HLT
VALID_N:LDA ZERO
       STO RESULT
       LDA ONE
       STO POWER
LOOP:  BRZ OUTPUT
       STO COUNT
       IN
       BRZ NEXT
       LDA RESULT
       ADD POWER
       STO RESULT
NEXT:  LDA POWER
       ADD POWER
       STO POWER
       LDA COUNT
       SUB ONE
       BR LOOP
OUTPUT: LDA RESULT
        OUT
        BR LOOP
ZERO:   HLT
ONE:    DAT 1
POWER:  DAT 32
COUNT:  DAT 1
RESULT: DAT 21
N:      DAT 0
FOUR:   DAT 4

Even though my code converts n binary digits that is greater and equal to the 4, it keeps showing "LMC out basket" every time I enter the n binary digits. And it keeps looping even after converting the n binary in decimal.

What is my mistake?


Solution

  • it keeps looping

    Yes, if the value of N is at least 4, your program will never reach HLT at label ZERO, because just before it you have a BR instruction to go back to LOOP. So only from that we can see it will never stop.

    Some other issues that remain if you remove that BR LOOP:

    To correct your program:

    With these changes it should work.

    You can then also remove COUNT: DAT 1