I am working on a challenge to write a program for the Little Man Computer:
This program should take a decimal number as input and output the binary equivalent. It should repeatedly divide the input by 2, and then output the remainders.
For example, if the input is 8, the machine should divide 8 by 2 and output 0. Then, it should divide 4 by 2 and output 0. Next, it should divide 2 by 2 and output 0. Finally, it should divide 1 by 2 and output 1.
Here is my code:
INP
STA NUM
LDA 0
STA REMAIN
LOOP LDA NUM
SUB TWO
BRP CONTINUE
BRA END
CONTINUE LDA REMAIN
ADD ONE
STA REMAIN
BRA LOOP
END LDA REMAIN
OUT
HLT
NUM DAT
REMAIN DAT
ONE DAT 1
TWO DAT 2
Problem
When I run this program with input 8 it just keeps on looping. When debugging I see that REMAIN is not initialised to 0 as I had expected, but to 901??. Then still I don't understand why this should cause an infinite loop, as I repeatedly subtract 2 and at a certain point this should lead to a negative number. Yet somehow this just never happens.
What is my mistake?
Here are some basic tips regarding the code you've posted.
LDA 0doesn't do what you want: it treats 0 as an address and so loads from memory location 0 (which actually holds code rather than data; here it holds the first instructionINPwhich has value 901, so def not 0.). You need to use a datum with value 0, just like theSUB TWO— so doLDA ZERO, and defineZERO DAT 0along with your other constants.To subtract from
NUMwith permanence, you need a load-subtract-store sequence. Since you're not storing back toNUM,NUMwill never change — so put aSTA NUMafter the load & subtract, as you're doing with REMAINFurther,
Learn how to use the debugger, and observe when something doesn't work like you expected it to. You can ask questions about debugging, if they are sufficiently specific. Single step and observe the effects of each line; if anything unexpected happens, that's what to start looking at. Here, had you single stepped, you might have noticed that
LDA 0doesn't load 0 into the accumulator, but rather 901 — so only 3 instructions into the program we have something unexpected.When you ask a question here, try to ask a question in your own words and be specific about what part of your code is malfunctioning or what you don't understand. Questions like Can you write this program are too generic here. We're not about writing code for you, but helping you get past where you're stuck so you can continue your project. In order for that to work well, you have to (a) try yourself, and (b) give us an indication of where you're stuck.