【问题标题】:NASM x86 print integer using extern printfNASM x86 使用 extern printf 打印整数
【发布时间】:2019-07-06 02:15:11
【问题描述】:

我尝试在 x86 程序集中使用 printf 打印一个整数。对于格式字符串printf(fmtstring, vals),我将%d 存储为fmtd。然后我将 1 放入 ax,2 放入 bx,添加它们并希望使用调用 printf 打印结果。这是代码。

global _main

extern _printf

section .data
    fmtd db "%d"

section .text

_main:
    push ebp
    mov ebp, esp

_begin:
    mov ax, 1
    mov bx, 2
    add ax, bx
    push ax
    push fmtd
    call _printf
    add esp, 8

_end:
    mov esp, ebp
    pop ebp
    ret

但我明白了

-10485757

而不是预期

3

你能帮我看看有什么问题吗?

刚写完的时候

push 3
push fmtd
call _printf

它照常工作并打印 3。

谢谢

【问题讨论】:

  • 如果你在做 32 位,那不应该是 mov eax,1mov ebx,2 等吗?
  • 我不能把一个 1 放入 16 位,让它看起来像00000000 00000001,右边是一个吗?我的情况是10000000 00000000 还是10000000 20000000
  • ...不要忘记push eax 而不是push ax
  • 不清楚您在评论中的要求。在您的代码中,您尝试从寄存器中打印 3 。 push ax 推送 16 位寄存器(2 字节),然后 push fmtd 推送 4 字节地址。您需要为%d 推送一个4 字节的值,即push eax。要清楚整个序列:mov eax,1mov ebx,2add eax, ebxpush eax 然后调用printf
  • -10485757 是十六进制的FF600003。这会响铃吗?

标签: c x86 nasm


【解决方案1】:

您需要使用完整的 32 位寄存器:

你想要这个:

mov eax, 1
mov ebx, 2
add eax, ebx
push eax
push fmtd
call _printf

输出-10485757你得到的解释:

十六进制的-10485757FF6000030003 来自push ax,它推动了eax 的16 个低位。 FF60 是堆栈中剩余的任何内容。

阅读this SO article了解axeax之间关系的详细解释。

【讨论】:

    猜你喜欢
    • 2013-12-14
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2015-09-17
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    相关资源
    最近更新 更多