gpt4 book ai didi

linux - 将用户输入读取为整数

转载 作者:太空宇宙 更新时间:2023-11-04 10:21:07 25 4
gpt4 key购买 nike

我写了一个汇编程序 (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”)被写入内存中的“数字”,每个字符一个字符。现在你有你想要解决的完全相反的问题:“如何将 ASCII 字符串转换为二进制值”

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

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

关于linux - 将用户输入读取为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43858176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com