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?
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
:
The instruction at LOOP: BRZ OUTPUT
will branch to OUTPUT
the second time it gets there. This is because the accumulator will have the value of COUNT
, which started as 1, and is decreased by 1 just before a jump back to LOOP
. This means that your program will only read one "bit" from the input, never reading the other bits that are remaining in the input.
After your program has checked that the first input is at least 4, it never looks at N
again, yet it needs it to know how many values to read from the input. You actually don't need COUNT
and instead should decrease N
until it is zero.
To correct your program:
STO COUNT
BR LOOP
that precedes the line ZERO: HLT
LDA COUNT
with LDA N
SUB ONE
add a line with STO N
With these changes it should work.
You can then also remove COUNT: DAT 1