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?