问题描述
我想将高级语言中的简单循环转换为汇编语言(对于 emu8086),比如说,我有这个代码:
I want to convert simple loops in high-level languages into assembly language (for emu8086) say, I have this code:
for(int x = 0; x<=3; x++)
{
//Do something!
}
或
int x=1;
do{
//Do something!
}
while(x==1)
或
while(x==1){
//Do something
}
我如何在 emu8086 中做到这一点?
How do I do this in emu8086?
推荐答案
For-loops:
C 中的 For 循环:
For-loops:
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
8086 汇编器中的相同循环:
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
如果您需要访问索引 (cx),这就是循环.如果你只想做 0-3=4 次但不需要索引,这会更容易:
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
如果您只想以恒定次数执行非常简单的指令,您还可以使用汇编指令,该指令只会对该指令进行硬核
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while 循环
C 中的 Do-while 循环:
Do-while-loops
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
汇编程序中的相同循环:
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While 循环
C 中的 while 循环:
While-loops
While-loop in C:
while(x==1){
//Do something
}
汇编程序中的相同循环:
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
对于 for 循环,您应该使用 cx 寄存器,因为它几乎是标准的.对于其他循环条件,您可以使用自己喜欢的寄存器.当然,用你想在循环中执行的所有指令替换无操作指令.
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
这篇关于汇编语言中的 While、Do While、For 循环 (emu8086)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!