Nasm print to next line

六眼飞鱼酱① 提交于 2021-02-10 07:11:36

问题


I have the following program written in nasm Assembly:

section .text
    global _start:

_start:
    ; Input variables
    mov edx, inLen
    mov ecx, inMsg
    mov ebx, 1
    mov eax, 4
    int 0x80

    mov edx, 2
    mov ecx, num1
    mov ebx, 0
    mov eax, 3
    int 0x80

    mov edx, inLen
    mov ecx, inMsg
    mov ebx, 1
    mov eax, 4
    int 0x80

    mov edx, 2
    mov ecx, num2
    mov ebx, 0
    mov eax, 3
    int 0x80

    ; Put input values in correct registers
    mov eax, [num1]
    sub eax, '0'    ; convert char to num
    mov ebx, [num2]
    sub ebx, '0'    ; convert char to num

    ; Perform addition
    add eax, ebx
    add eax, '0'    ; convert num to char

    ; Set sum in res
    mov [res], eax

    ; Output result
    mov edx, resLen
    mov ecx, resMsg
    mov ebx, 1
    mov eax, 4
    int 0x80

    mov edx, 1
    mov ecx, res
    mov ebx, 1
    mov eax, 4
    int 0x80

    ; Exit program
    mov eax, 1
    int 0x80

    section .bss
    num1    resb 2
    num2    resb 2
    res resb 2

section .data
    inMsg db "Input number: ", 0xA, 0xD
    inLen equ $-inMsg
    resMsg db "Result: ", 0xA, 0xD
    resLen equ $-resMsg

When I run it the console looks like this:

tyler@ubuntu:~/ASM/Addition$ ./Add 
Input number: 
3
Input number: 
2
Result: 
5tyler@ubuntu:~/ASM/Addition$ 

How can I get it so the 5 will print on its own line and not have the cmd print directly after it? I.E. it should look like this:

tyler@ubuntu:~/ASM/Addition$ ./Add 
Input number: 
3
Input number: 
2
Result: 
5
tyler@ubuntu:~/ASM/Addition$ 

回答1:


You have all the info already, you just don't see it yet:

resMsg db "Result: ", 0xA, 0xD

Do you know what this means exactly? It defines a string made of the following characters:

Result: XY

...where X and Y are actually invisible characters (with numerical values 0xA=10 and 0xD=13, also known as line feed (LF) and carriage return (CR)) which cause the output to wrap to a new line. They are specified outside of the doublequotes because of their invisible nature - you can't just include them there so you have to write their numerical values instead.

But of course you can use them alone as well:

newLineMsg db 0xA, 0xD
newLineLen equ $-newLineMsg

(newLineLen will be 2 of course but I left it here to keep the system the same as you currently use, for easier understanding.)

So to just output a line break without any other text (what you want to do after the 5), you can then use:

mov edx, newLineLen
mov ecx, newLineMsg
mov ebx, 1
mov eax, 4
int 0x80

...just like with resMsg/resLen.


However, as Jester pointed out, on Linux you should also be able to output just a single line feed (0xA) (and also remove the existing 0xD's from your code).



来源:https://stackoverflow.com/questions/36881270/nasm-print-to-next-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!