简体   繁体   中英

How to write a If, Else if in assembly

I need to convert the following C code to its equivalent in Assembly. 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.

    .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.

EDIT: Corrections/ explanations are in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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