Showing that c = |a - b | using assambly with limited operations

84 views Asked by At

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.

1

There are 1 answers

0
Ped7g On BEST ANSWER

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:

  do { dec a, dec b } while jnz
  ; that will achieve: a = a-b, b = 0

  ; set b = a, d = -a
set_b_and_d_from_a:
  inc b
  dec d
  dec a
  jnz set_b_and_d_from_a

find_positive_value:
  inc c
  dec b
  jnz find_positive_value_try_d_too
  halt  ; c = |a-b| for (a-b) >= 0
find_positive_value_try_d_too:
  dec d
  jnz find_positive_value
  halt  ; c = |a-b| for (a-b) < 0
; the positive value will take fewer "dec" to reach
; so one of the halt is reached sooner
; with "c" set to the number of "dec" used

Don't do "label1" to "label4", give them some meaning, what they are doing.