How to print a string inside of a loop in assembly (MASM)

冷暖自知 提交于 2019-12-11 10:38:45

问题


So I'm new to assembly, and my professor is far from helpful when it comes to actually explaining what's happening.

In class, we set up loops like this:

mov si, 0
mov cx, 5 (repeating the loop 5 times)

L1:
   ...
   loop L1

And we print strings like this:

mov ah, 40h                 ;write to 
mov bx, handle              ;file
mov cx, lmess2              ;number of bytes to write
mov dx, offset mess2        ;
int 21h

So now the issue is that I need to print a string inside the loop. The issue I see with this is that the CX register is used in both the string printing and the loop, so when I try running it, it hangs, as expected.

Is there a different register/method I can use for the loop and the string printing?

Perhaps I can compare the value of the SI register to however many iterations of the loop I want, and then use a JE jump to jump out of the loop? But to me that seems a bit odd.

If anyone could guide me in the right direction, I'd greatly appreciate it. I'm sure there's an easy way to do this that I'm overlooking.


回答1:


Two solutions :

SOLUTION #1

mov si, 0
mov bp, 5  ;DON'T USE CX, USE AN UNUSED REGISTER, LIKE BP.

L1:
   ...
   dec  bp      ;BP - 1. Zero-Flag turns on when BP becomes zero.
   jnz  L1      ;IF BP != 0 JUMP L1. JNZ = jump if last result is not zero.

SOLUTION #2

mov si, 0
mov cx, 5 (repeating the loop 5 times)

L1:
   PUSH CX         ;PRESERVE CX BEFORE IT CHANGES.
   ... ;PRINT HERE.
   POP  CX         ;RESTORE CX FOR PREVIOUS VALUE.
   loop L1

The chosen solution depends on the situation : using registers is the fastest way, pushing-popping is slower (because of stack). If you have unused registers, use them, it's faster, if you don't, use stack.



来源:https://stackoverflow.com/questions/29655190/how-to-print-a-string-inside-of-a-loop-in-assembly-masm

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