c - 试图将 C 程序翻译成 x86 汇编

标签 c assembly x86 att

我正在尝试将以下程序转换为 x86 汇编 ( AT&T )。

#include <stdio.h>

int main()
{
   int n = 123;
   int reverse = 0;


   while (n != 0)
   {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n       = n/10;
   }

   printf("%d\n", reverse);

   return 0;
}

它应该打印 321。

但是,使用下面的代码,我得到的是 0。 谁能告诉我我在这里做错了什么? (我只粘贴了下面的相关部分。我确信初始化和打印工作正常。你可以看到 the whole thing here )

  movl  $123, %esi    # int n
  movl  $0, %edi    # int reverse
  movl $10, %ebx    # divisor


L1:     # while n != 0

cmpl $0, %esi
je L2

# reverse = reverse * 10
imul $10, %edi

# reverse = reverse + n % 10
movl $0, %edx
movl %edi, %eax
idivl %ebx
addl %edx, %edi

# n = n / 10
movl %esi, %eax
movl $0, %edx
idivl %ebx
movl %eax, %esi

jmp L1

L2:  # end while

movl %edi, %eax

也许我还没有完全理解 idivl 命令应该做什么。我知道它将 %edx:%eax 除以 %ebx,并将商存储在 %eax 中,将余数存储在 %edx 中。

最佳答案

# reverse = reverse + n % 10
movl $0, %edx
movl %edi, %eax   ; <--- here

%edi 不是n,根据上面的注释:

movl  $123, %esi    # int n

因此,它应该使用 %esi,即 movl %esi, %eax

关于c - 试图将 C 程序翻译成 x86 汇编,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941176/

相关文章:

assembly - 在汇编中清除寄存器中的位

c - 用 C 将项目插入堆栈

c - 堆栈内存使用连续动态分配的数组与静态

c++ - 来自 QFile 的 QByteArray

linux - ELF header ,偏移量 06h 和 14h 是否重复?

c - GCC 裸机内联汇编 SI 寄存器与指针不能很好地配合

c - 在 OpenACC pragma 行中使用结构数据类型

assembly - push 和 pop 在 assembly 中是如何工作的

c++ - 为什么向 C++ 代码添加 "if"会使其速度显着加快?

assembly - NASM 汇编器 - 如何确保函数标签不会被额外执行一次?