2017-05-08 19 views
0

我寫了一個彙編程序(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 

等等。

如果你們中的一些人對第二種情況下的問題有所瞭解,以及如何解決,我將不勝感激。

+1

對於輸入您需要從文本轉換爲數字(與輸出轉換相反)。對於'0'輸入,你得到'2608',因爲你的輸入是'0'的ASCII碼,它是'48',後面跟着一個以'10'爲代碼的換行符,並且'48 + 10 * 256 = 2608'小端。 – Jester

+0

@Jester所以在這種情況下,我必須從餘數中減去48('0'的ASCII碼)。那是對的嗎?我錯過了別的嗎? – Jazz

+1

是的,對於多位數字,您當然需要通過10的適當冪進行縮放,並且顯然忽略換行。在輸出期間你不這樣做,這是一個輸入轉換,沒有「餘數」。 – Jester

回答

1

當你調用這個

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

是,你的條目(例如「1004」)在「數量」寫入存儲器什麼happends,每個字符的字符。現在,你有打算解決完全相反的問題: 「如何將ASCII字符串轉換爲二進制值」

算法爲這個新的問題看起來是這樣的:

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