/* sum = a*b - no overflow */
bs = b
as = a
sum = 0
if (low bit as is 1)
sum = sum + bs
shift as right
shift bs left
....
sum = 0
if (high bit a = 1)
sum = sum + b
shift sum left
shift a left
.....
This is a program that pushes the two numbers to be multiplied onto the stack and calls the MULTIPLY function. The result of the multiply is in the accumulator on return.
The first two instructions are used to initialize the stack pointer (SP) to high memory. The stack looks like:
| |
|-----------|
4095 | | <- SP
-----------
The two parameters of MULTIPLY are pushed on the stack before the call:
4092 | |
|-----------|
4093 | 78 | <- SP
|-----------|
4094 | 119 |
|-----------|
4095 | |
-----------
At the beginning the MULTIPLY, the stack looks like:
4091 | |
|-----------|
4092 | ret addr | <- SP
|-----------|
4093 | 78 |
|-----------|
4094 | 119 |
|-----------|
4095 | |
-----------
Before MULTLOOP the stack looks like:
|-----------|
4090 | 0 | <- SP [sum at SP + 0]
|-----------|
4091 | 0 | [i at SP + 1]
|-----------|
4092 | ret addr |
|-----------|
4093 | 78 | [b at SP + 3]
|-----------|
4094 | 119 | [a at SP + 4]
|-----------|
4095 | |
-----------
MAIN:
LOCO 4095 ! Set stack pointer to 4095 to start program
SWAP
LOCO 119 ! a <- 119
PUSH
LOCO 78 ! b <- 78
PUSH
CALL MULTIPLY ! Multiply 119*78
JUMP 4095 ! End the program
MULTIPLY:
LOCO 0
PUSH ! i = 0
PUSH ! sum = 0
MULTLOOP:
LOCO 15 ! ac <- 15
SUBL 1 ! ac <- 15 - i
JZER DONE ! if (i = 15) go to DONE
LODL 4
JPOS DONEADD ! if (a >= 0) go to DONEADD
LODL 3
ADDL 0
STOL 0 ! sum <- b + sum
DONEADD:
LODL 0
ADDL 0
STOL 0 ! shift sum left one bit
LODL 4
ADDL 4
STOL 4 ! shift a left one bit
LOCO 1
ADDL 1
STOL 1 ! i++
JUMP MULTLOOP
DONE:
LODL 4
JPOS NOADD ! if (a >= 0) goto NOADD
LODL 3
ADDL 0
STOL 0 ! sum <- b + sum
NOADD:
LODL 0 ! return result in ac
INSP 2 ! fix stack so return address is on top
RETN