将用户输入读取为整数

Reading user input as an integer

我写了一个汇编程序 (x86_64 Linux NASM),它打印一个整数到控制台,基于算法建议我在这个 post 中的评论,基本上是这样的:

divide number x by 10, giving quotient q and remainder r
emit r
if q is not zero, set x = q and repeat

在以下脚本下一切正常:

section .bss
        integer resb 100        ; it will hold the EOL
        intAddress resb 8       ; the offset

section .text

        global _start:

_start:

        mov rax, 567
        call _printProc

        mov rax, 60
        mov rdi, 0
        syscall


_printProc: ; here goes the algorithm described above.

编译后,数字 567 打印在屏幕上(控制台)。

但是,如果我尝试做同样的事情,但允许用户输入要打印为整数的数字,我就不会得到预期的结果。好吧,为此我做了以下更改(算法保持不变):

section .bss
        integer resb 100        ; it will hold the EOL
        intAddress resb 8       ; the offset
        number resb 100

section .text

        global _start:

_start:

        ; getting user input
        mov rax, 0
        mov rdi, 0
        mov rsi, number
        mov rdx, 100
        syscall

        mov rax, [number]       ; passing the content at address number into rax
        call _printProc

        mov rax, 60
        mov rdi, 0
        syscall


_printProc: ; here goes the algorithm described above.

但在这种情况下,如果我输入 567,我会得到 171390517。事实上,如果我输入

0, I get 2608
1, I get 2609
2, I get 2610

等等。

如果你们中的一些人知道第二种情况的问题是什么以及如何解决,我将不胜感激。

当你调用它时会发生什么

    ; getting user input
    mov rax, 0
    mov rdi, 0
    mov rsi, number
    mov rdx, 100
    syscall

是,您的条目(例如“1004”)被写入 "number" 处的内存,每个字符一个字符。现在你有你想要解决的完全相反的问题: "how to convert an ASCII string into binary value"

这个新问题的算法可能如下所示:

(assuming char_ptr points to the string)
result = 0;
while ( *char_ptr is a digit )
    result *= 10;
    result += *char_ptr - '0' ;
    char_ptr++;