gnu-assembler - 汇编语言从0递增到100

标签 gnu-assembler assembly

这有点奇怪,但是我今天正在玩GNU汇编器(我希望至少能够读懂语法),并试图让我的这个小小的人为例子工作。即我只想从0到100,一直打印出数字。所以几分钟后,我想到了这个:

# count.s: print the numbers from 0 to 100. 
    .text
string: .asciz "%d\n"
    .globl _main

_main:
    movl    $0, %eax # The starting point/current value.
    movl    $100,   %ebx # The ending point.

_loop:
    # Display the current value.
    pushl   %eax
    pushl   $string
    call     _printf
    addl     $8, %esp

    # Check against the ending value.
    cmpl    %eax, %ebx
    je    _end

    # Increment the current value.
    incl    %eax
    jmp _loop   

_end:

我从中得到的就是一遍又一遍地打印3遍。就像我说的,只是一个人为的例子,所以不必太担心,这不是生死攸关的问题。

(格式有点困惑,但没什么大不了的)。

最佳答案

您不能相信任何调用过程对任何寄存器的作用。
要么在调用printf之后将寄存器压入堆栈,然后将其弹出弹出,要么将增量和端点值保存在内存中,并根据需要将它们读/写到寄存器中。

希望以下作品。我假设pushl有一个等价的popl,并且您可以将另外两个数字压入堆栈。

# count.s: print the numbers from 0 to 100. 
    .text
string: .asciz "%d\n"
    .globl _main

_main:
    movl    $0, %eax # The starting point/current value.
    movl    $100,       %ebx # The ending point.

_loop:
    # Remember your registers.
    pushl   %eax
    pushl   %ebx

    # Display the current value.
    pushl   %eax
    pushl   $string
    call     _printf
    addl     $8, %esp

    # reinstate registers.
    popl   %ebx
    popl   %eax

    # Check against the ending value.
    cmpl    %eax, %ebx
    je    _end

    # Increment the current value.
    incl    %eax
    jmp _loop   

_end:

关于gnu-assembler - 汇编语言从0递增到100,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19409/

相关文章:

c - 为什么我不能从这个 C 代码访问在汇编中声明的 Tss 变量?

assembly - .code16 和 .code32 有什么区别

gcc - 使用 GCC(内联汇编程序)将双倍加载到 FPU

regex - Bash - 如何计算指令数?

assembly - 68K 汇编中的模数

linux - 在程序集中将数组传输到数组得到奇怪的输出。为什么?

assembly - 如何在 GAS 汇编程序中导出函数?

c - 如何用C写rotate代码编译成 `ror` x86指令?

linux - 是否可以使用 `as` 组装和运行原始 CPU 指令?

assembly - 编写一个简单的引导加载程序来读取用户名