LC3 Assembly Square of N

梦想的初衷 提交于 2020-01-25 22:54:28

问题


Hi I'm trying to write a lc3 assembly program which computes the square of a number and stores it in r0, the integer is given as a parameter and is located in r1, the problem i noticed while debugging is during the first pass it initially adds 2, but the second pass it fails to add another 2 to r0 - My code is below any help is appreciated

           .orig x3FF8
      ld r1,n
    ld r5,n

  square
 add r2,r1,#0

  add r5,r5,#-1
add r0,r2,#0
brzp square
brn theend

  theend


halt
 n .fill #2

 .end

my final code thanks to the user who helped:

    .orig x3FF8
     ld r1,n
    ld r5,n

   square


  add r2, r2,r1

  add r5,r5,#-1

  brp square


  theend


 halt
  n .fill #4

 .end

回答1:


If I remember LC-3 syntax correctly, add r2,r1,#0 does r2 = r1 + 0, so it was never actually adding to r2, just overwriting it with r1.

You want something like that outside the loop to initialize r2.

But inside the loop, you want add r2, r2, r1 which does r2 = r2 + r1, i.e. r2 += r1.


I don't understand why you have add r0,r2,#0 inside the loop as well. If you want the final result in r0, accumulate it in r0 in the first place. Of if that was supposed to be a sum of sums, then you have the same bug.

Also note that add r5,r5,#-1 needs to be last so condition code flags are set from it for the loop branch, not from add r0, r0, r2 or whatever else you need inside the loop.


Also: brn theend is totally useless: theend is on the next line, and execution continues to the next line on its own. You don't have to jump over whitespace in the source!



来源:https://stackoverflow.com/questions/47765417/lc3-assembly-square-of-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!