使用printf asm nasm在一行上打印整个数组

时间:2015-02-11 19:07:34

标签: arrays assembly syntax printf 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

3 个答案:

答案 0 :(得分:1)

唯一确定是在一行还是多行打印某些内容的因素是,是否打印换行符(\n)。

此处,当您说10时,这是换行符的ASCII值。如果你改变了这个:

aoutput: db "%d", 10, 0 

到此:

aoutput: db "%d ", 0 

您的值将以空格分隔,而不是换行。

在序列中的最终值之后,您可以打印一个单独的换行符:

push 0x0A     ; New line character
call putchar

答案 1 :(得分:0)

我想出了这个(这与其他答案相同,我只是在看到它发布之前才发现它。)

我想通了,我将格式定义更改为:

 aoutput: db "%d ", 0   ; output format

从:

 aoutput: db "%d ", 10, 0   ; output format

并添加了换行符格式,以便在最后添加新行。

 newline: db "", 10, 0    ; newline format

答案 2 :(得分:0)

问题是您在每个元素后输出换行符。

以下是两种解决方案。他们都没有像现有的两个解决方案那样留下尾随空白的问题。

请注意,我对循环进行了轻微的重新排列以允许空数组。允许空数组是一种很好的做法,即使它没有必要,因为它不需要任何额外的指令。


解决方案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

如果您不想打印空数组的换行符,这很好。

"%d"

解决方案2:如果它是第一个元素,请使用" %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 作为格式。循环后打印换行符。

如果您想打印换行,即使是空数组也是如此。

eax

原谅任何错误;上次为它编写程序集时,x86没有{{1}}寄存器。无论如何,逻辑应该是显而易见的。