I need to write an assembly code that returns c = |a - b |. The only orders I am allowed to use are:
INC
- Raising the value stored in one register.
DIC
- Reducing the value stored in one register.
JNZ
-Jump to a point in the code (LABEL). As long as the last operation was done near the line of code is not equal to zero.
HALT
- Stopping the code.
You can use as much registers as you want (it is preferable as to use as less as possible) and the values of all the registers is initialized to zero.
I am trying to do this but unfortunately I get stuck everytime. that's what I currently have:
Label 3
Dec a
Jnz label 1
Label 2
Inc c
Dec b
Jnz label 2
Dec c
Halt
Label 1
Dec b
Jnz label3
Label4
Inc c
Dec a
jnz label4
Halt
This is only for positive numbers, I have now Idea what I should do for negative numbers.
Did you debug it for negative values? Looks to me like for some combinations it may actually work by warping around correctly. Then again for some others it will not, like |5-0|.
I assume you are talking about real-like binary CPU architecture, where numbers have only fixed amount of bits and negative values are encoded as two's complement, so "warping" around works.
So... I think you can do this:
Don't do "
label1
" to "label4
", give them some meaning, what they are doing.