【问题标题】:While, Do While, For loops in Assembly Language (emu8086)汇编语言中的 While、Do While、For 循环 (emu8086)
【发布时间】:2015-04-24 06:56:41
【问题描述】:

我想将高级语言中的简单循环转换为汇编语言(对于emu8086),比如说,我有这个代码:

 for(int x = 0; x<=3; x++)
 {
  //Do something!
 }

 int x=1;
 do{
 //Do something!
 }
 while(x==1)

 while(x==1){
 //Do something
 }

如何在 emu8086 中执行此操作?

【问题讨论】:

  • 假设您已经知道如何在汇编中实现比较和条件跳转,请先使用ifgoto 重写代码和/或创建流程图。
  • 不!仅适用于emu8086!
  • 但是在emu8086中,我只能使用ax、bx、cx和dx! ecx 不存在?
  • 只要把注册名中的 e 去掉即可。 e 代表扩展(我相信) - 它表示 32 位宽的寄存器而不是 16 位。

标签: loops for-loop assembly while-loop x86-16


【解决方案1】:

For 循环:

C 中的 For 循环:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

8086 汇编器中的相同循环:

        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 次但不需要索引,这会更容易:

        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

如果您只想以恒定的次数执行一条非常简单的指令,您还可以使用汇编器指令,该指令将硬核该指令

times 4 nop

执行循环

在 C 中执行循环:

int x=1;
do{
    //Do something!
}
while(x==1)

汇编器中的相同循环:

        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(x==1){
    //Do something
}

汇编器中的相同循环:

        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-register,因为它非常标准。对于其他循环条件,您可以根据自己的喜好进行注册。当然,将无操作指令替换为您要在循环中执行的所有指令。

【讨论】:

  • 在 asm 中,尽可能使用 do{}while() 循环结构,for the same reason compilers do:代码运行得更快,循环内的指令更少。 (通常剥离运行零次检查比跳到循环底部要好,就像您在 while 循环中所做的那样。)
  • 这里的for 循环代码是错误的。它应该在循环的第一次迭代之前跳转到循环条件检查。
  • @ecm:这并不是严格的错误,它应用了x&lt;=3 在第一次迭代中已知为真的优化,允许跳过该检查。当您知道它们将至少运行一次时,这是 100% 标准和惯用的,因为有固定的循环边界。其他类型的 for 循环有时可能需要运行 0 次,但这个答案是关于遵循从 0 .. n 循环 x 的惯用模式的 for 循环。
【解决方案2】:
Do{
   AX = 0
   AX = AX + 5
   BX = 0
   BX= BX+AX 
} While( AX != BX)

执行while循环总是在每次迭代结束时检查循环条件。

【讨论】:

    猜你喜欢
    • 2015-02-13
    • 1970-01-01
    • 2017-03-08
    • 2020-08-26
    • 2013-08-28
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多