如何在程序集(MASM)中的循环内部打印字符串 [英] How to print a string inside of a loop in assembly (MASM)
问题描述
所以我刚接触汇编,而我的教授在实际解释正在发生的事情时远没有帮助.
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
所以现在的问题是我需要在循环内打印一个字符串.我看到的问题是在字符串打印和循环中都使用了CX寄存器,因此当我尝试运行它时,它会按预期方式挂起.
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?
也许我可以将SI寄存器的值与所需的循环次数进行比较,然后使用JE跳转来跳出循环?但是在我看来,这有点奇怪.
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
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.
解决方案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.
这篇关于如何在程序集(MASM)中的循环内部打印字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!