assemblynewlinenasmmachine-instruction

Newline not executing properly using nasm for x86 architecture


I am using the instruction 0xa at the end of a string to create a newline so that the last string printed does not run into the next.

mov bx, MESSAGE
call print_string

mov bx, ANOTHER
call print_string

hlt

print_string:
    pusha

    string_loop:
        mov al, [bx]
        cmp al, 0
        jne print_char

        popa
        ret

        print_char:
            mov ah, 0x0e
            int 0x10
            add bx, 1
    jmp string_loop

;global vars
MESSAGE: db 'Example string',0xa,0
ANOTHER: db 'Another example string',0xa,0

;padding/magic number
times 510-($-$$) db 0
dw 0xaa55

The only problem is that, while the strings do indeed print one line below the last, the new line does not reset the x position on the screen, so instead of printing directly below the previous string, it prints below and just after the previous string.

example output:

Example string
              Another example string

How do I write this code so that strings print directly under the previous string?


Solution

  • What to do with Jester's comment (add carriage return alongside linefeed):

    MESSAGE: db 'Example string',13,10,0
    ANOTHER: db 'Another example string',13,10,0
    

    What to do with Ped7g's comment (change BX into SI and setup the BL and BH arguments):

    mov bx, 0007h       ;Display page 0, graphics color 7
    mov si, MESSAGE
    call print_string
    ...
    string_loop:
        mov al, [si]
        ...
        add si, 1
        jmp string_loop
    

    Since this is bootloader code (times 510-($-$$) db 0 dw 0xaa55) and that ORG 0 is the default, you should best explicitely set the DS segment register at zero. Don't trust your executing environment for this!

    xor     ax, ax
    mov     ds, ax
    

    Put this before anything else.