assembly - 对 10 个数字求和并在 NASM 中打印结果

标签 assembly x86 nasm

我编写了以下用于添加 10 个数字的汇编代码。我能够编译并执行它,但得到错误的结果。 我只是想知道如何在屏幕上打印总计的值。

section .data
num1: dw 10, 20, 30, 40, 50, 10, 20, 30, 40, 50
total: dw 0
msg :  db "sum=%d",10,0

section .text
    extern _printf
    global _main
_main:
    push ebp
    mov ebp,esp
    mov ebx,num1 ;point bx to first number
    mov ecx,10      ;load count of numbers in ecx
    mov eax,0       ;initialize sum to zero
loop:
    add eax,[ebx]
    add ebx,2
    sub ecx,1
    jnz loop
    mov [total],eax

    push total
    push msg
    call _printf

    pop ebp
    mov esp,ebp
    ret

解决方案

section .data
num1: dd 10, 20, 30, 40, 50, 10, 20, 30, 40, 50,300
total: dd 0
msg :  dd "sum=%d",10,0

    section .text
        extern _printf
        global _main
    _main:
        push ebp
        mov ebp,esp
        mov ebx,num1 ;point bx to first number
        mov ecx,11     ;load count of numbers in ecx
        mov eax,0       ;initialize sum to zero
    loop:
        add eax,[ebx]
        add ebx,4
        sub ecx,1
        jnz loop
        mov  [total],eax
        push dword [total]

        push msg
        call _printf
        mov esp,ebp
        pop ebp

        ret

最佳答案

我在这里看到几个问题。首先,您将 num1total 声明为 dwdw 听起来可能意味着“dword”,但它的意思是“数据字”。您希望这些是 dd - “data dword”...因为这就是您使用它们的方式。 (并且添加 ebx, 4 而不是 2)如果您确实需要在 32 位代码中使用字(16 位)值,可以这样做,但很尴尬。

我看到的第二个问题是,在调用_printf推送total的地址之前push total。您想要此处的内存“[内容]”,因此push dword [total]。 (推送消息正确)

在此之后,您可能需要 add esp, 8 (我喜欢将其写为 add esp, 4 * 2 - 两个参数,每个参数 4 个字节)。可以“推迟”此堆栈清理 - mov esp, ebp 会修复您的问题,但需要在 pop ebp 之前完成!!!

...可能还有更多...

关于assembly - 对 10 个数字求和并在 NASM 中打印结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14215961/

相关文章:

assembly - XOR寄存器,寄存器(汇编器)

assembly - 使用Intel SIMD SSE加载非连续值

assembly - 在 NASM 中使用 OR r/m32、imm32

label - NASM - 从现有标签创建新标签

assembly - 目标文件中的符号表和重定位表

assembly - x86_64 汇编命令行参数

linux nasm程序集查找变量中保存的位数

c - 将 C 函数的值返回给 ASM

c - asm 语法高亮和 asm 文件在 Visual Studio 中显示

assembly - 在 x86 汇编中将 ASCII 转换为二进制的最有效方法