简体   繁体   English

如何在汇编中编写If,Else if

[英]How to write a If, Else if in assembly

I need to convert the following C code to its equivalent in Assembly.我需要将以下 C 代码转换为汇编中的等效代码。 I've only taken a few classes on assembly and don't really have a grasp of the language yet.我只上过几节汇编课程,还没有真正掌握这门语言。


int x = 45
int y = 27
while (x != y) {
   if (x > y)
      x = x - y;
   else if (y > x)
      y = y - x;
}  
return x;  // Sends exit code containing GCD

I have written what i believe to work and am about to use a debugger to find inevitable flaws but wanted to ask if i am headed in the right direction with the if else statement.我已经写了我认为可行的东西,并且即将使用调试器来查找不可避免的缺陷,但想问问我是否使用 if else 语句朝着正确的方向前进。

    .global _start
    _start

    mov R1, #45  @R1 = 45
    mov R2, #27  @R2 = 27

    loopTop:
    cmp R1, R2
    beq allDone
    bge R1,R2
    sub R1,R1,R0
    bge R2,R1
    sub R2,R2,R1
    b loopTop


    allDone:
    SWI R1

Any help/tips would be greatly appreciated!任何帮助/提示将不胜感激! Thanks!谢谢!

Here's your solution:这是您的解决方案:

mov R1, #45 @x
mov R2, #27 @y

loop:
    cmp R1, R2  @compare R1 with R2
    bne label1  @is R1 not equals to R2? "Branch is Not Equal" to label1, else...

    @<replace with the return R1 statement here>

    label1:
        cmp R1, R2
        bgt sub_xy  @"Branch on Greater Than"
        cmp R1, R2
        blt sub_yx  @"Branch on Lower Than"

    sub_xy:
        sub R1, R1, R2  @R1 = R1 - R2
        b loop  @branch to loop

    sub_yx:
        sub R2, R2, R1  @R2 = R2 - R1
        b loop

Came up with this as a newb x86_64 programmer trying to code for ARM for the first time.作为一个新的 x86_64 程序员第一次尝试为 ARM 编码,想出了这个。

EDIT: Corrections/ explanations are in the comments.编辑:更正/解释在评论中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM