[英]Printing an entire array on a single line using printf asm nasm
我正在使用NASM來編譯我的ASM程序,但是我很難弄清楚如何使用循環在一行上打印整個陣列(不必知道該陣列有多大)。 每當我用printf創建一個循環時,它都會在多行而不是一行上打印值。 任何想法如何使printf使用循環在一行上打印數組的多個值? 我得到的值是1-9,但都在不同的行而不是同一行。 無需使用除printf c庫以外的外部庫即可完成此操作。 非常感激任何的幫助。 我的代碼如下。
extern printf
SECTION .data ; Data section, initialized variables
array: dd 1, 2, 3, 4, 5, 6, 7, 8, 9, 0; this is a test array for testing purposes
arrayLen: dd 9 ; length of array
aoutput: db "%d", 10, 0 ; output format
SECTION .text ; Code section.
global main ; the standard gcc entry point
main: ; the program label for the entry point
push ebp ; set up stack frame
mov ebp,esp
mov ecx, [arrayLen] ; loop counter set up
mov esi, 0 ; counter to increment set up for looping through array
.loop:
push ecx ; make sure to put ecx (counter) on stack so we don't lose it when calling printf)
push dword [array + esi] ; put the value of the array at this (esi) index on the stack to be used by printf
push dword aoutput ; put the array output format on the stack for printf to use
call printf ; call the printf command
add esp, 8 ; add 4 bytes * 2
pop ecx ; get ecx back
add esi, 4
loop .loop
mov esp, ebp ; takedown stack frame
pop ebp ; same as "leave" op
mov eax,0 ; normal, no error, return value
ret ; return
決定是將一行打印還是多行打印的唯一方法是是否打印換行符( \\n
)。
在這里,當您說10
,這是換行的ASCII值。 如果您更改此設置:
aoutput: db "%d", 10, 0
對此:
aoutput: db "%d ", 0
您的值將用空格(而不是換行)分隔。
在序列的最終值之后,您可以打印一個孤獨的換行符:
push 0x0A ; New line character
call putchar
我發現了這一點(與其他答案相同,只是在看到它發布之前就發現了)。
我知道了,我將格式定義更改為:
aoutput: db "%d ", 0 ; output format
從:
aoutput: db "%d ", 10, 0 ; output format
並添加了換行符格式以在末尾添加新行。
newline: db "", 10, 0 ; newline format
問題是您要在每個元素之后輸出換行符。
以下是兩個解決方案。 正如現有的兩個解決方案一樣,它們都沒有留下尾隨空白的問題。
請注意,我對循環進行了一些重新排列,以允許使用空數組。 即使沒有必要,允許空數組也是一種好習慣,因為它不需要任何額外的說明。
解決方案1:如果它是最后一個元素,則使用"%d\\n"
作為格式,否則使用"%d "
。
如果您不想為空數組打印換行符,這很好。
format1: db "%d ", 0
format2: db "%d", 10, 0
jmp .loop3
.loop1:
mov eax,format1
cmp ecx,1
jnz .loop2
mov eax,format2
.loop2
push ecx
push dword [array + esi]
push dword eax
call printf
add esp, 8
pop ecx
add esi, 4
.loop3:
loop .loop1
解決方案2:如果是第一個元素,請使用"%d"
作為格式。 否則,請使用" %d"
作為格式。 在循環之后打印換行符。
如果您要打印換行符(即使是空數組)也很好。
format1: db "%d", 0
format2: db " %d", 0
mov eax, format1
jmp .loop2
.loop1:
push ecx
push dword [array + esi]
push dword eax
call printf
add esp, 8
pop ecx
add esi, 4
mov eax, format2
.loop2:
loop .loop1
push 10
call putchar
請原諒任何錯誤; 我上次為它編寫程序集時,x86沒有eax
寄存器。 在任何情況下,邏輯都應顯而易見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.