问题
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