使用printf在装配NASM中打印号码 [英] Printing a number in assembly NASM using printf
问题描述
一段时间以来,我一直在尝试使它打印12345.谁能提供我应该怎么做的提示?它将打印三行文本,然后在第四行上打印"age",我猜这是第二行中堆栈中的剩余内容.
I've been trying to get this to print 12345 for a while now. Can anyone provide a hint as to what I should do? It will print the three lines of text, then on the fourth line prints "age", which I'm guessing is a remnant in the stack from line 2.
bits 64
global main
extern printf
section .text
main:
; function setup
push rbp
mov rbp, rsp
sub rsp, 32
;
lea rdi, [rel message]
mov al, 0
call printf
;above code correctly prints message
;where the issue lies
push rbp
mov rbp, rsp
;sub rsp, 32
mov rax, 12345
;push rax
mov al,0
call printf
; function return
mov eax, 0
add rsp, 32
pop rbp
ret
section .data
message: db 'Lab 3 - Modified Hello program',0x0D,0x0a,'COSC2425 - Pentium assembly language',0x0D,0x0a,'Processed with NASM and GNU gcc',0x0D,0x0a
count dq 12345
推荐答案
显然,您甚至都不知道printf
的工作方式,这使得很难从汇编中调用它.
Apparently you don't even know how printf
works which makes it hard to invoke it from assembly.
要打印数字,printf
需要两个参数,即格式字符串和要打印的数字.例如:printf("%d\n", 12345)
.
To print a number, printf
expects two arguments, a format string and the number to print of course. Example: printf("%d\n", 12345)
.
现在要将其转换为汇编,您显然需要声明该格式字符串,然后使用适当的约定传递这两个参数.
Now to turn that into assembly, you obviously need to declare that format string, and then pass both arguments using the appropriate convention.
由于您似乎正在使用sysv abi,因此这意味着前两个参数分别进入rdi
和rsi
.您似乎已经知道必须将al
设置为零以表示未使用SSE寄存器.因此,相关部分可能如下所示:
Since you seem to be using sysv abi, this means the first two arguments go into rdi
and rsi
, respectively. You already seem to know you have to zero al
to indicate no SSE registers used. As such, the relevant part could look like:
lea rdi, [rel fmt]
mov rsi, 12345 ; or mov rsi, [count]
mov al, 0
call printf
...
fmt: db "%d", 0x0a, 0
这篇关于使用printf在装配NASM中打印号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!