2014-10-19 26 views
0

我正在嘗試在NASM程序集中編寫一個將十進制數轉換爲二進制數的程序。 到目前爲止,我編寫了一些採用輸入數字的代碼,將其除以2並顯示餘數。但我有一個問題,我得到分割後的無限循環,其實我一直在EAX一個大於0在組件分割後的無限循環NASM

; ---------------------------------------------------------------------------------------- 
; nasm -felf decbin.asm && gcc decbin.o -o decbin 
; ---------------------------------------------------------------------------------------- 
section .data 
    in_message db "Enter a number in decimal:",0 ;input message 
    out_message db "The binary number is:%d",10,0 ;output message 
    integer times 4 db 0     ;32bits integer 
    formatin db "%d",0 
    binary  db 2;used for div 
section .text 
    global main 
    extern printf 
    extern scanf 
main: 
;;; Ask for integer 
    push in_message 
    call printf 
    add esp,4  ;remove parameters 

    push integer  ;address of integer where number will be stored 
    push formatin ;%d parameter, arguments are right to left 
    call scanf 
    add esp,8  ;remove parameters 

    mov eax,[integer] 
    jmp loop 
    ;;; terminate if zero 
    mov al,1 
    mov ebx,0 
    int 80h 
loop: 
    xor edx,edx 
    mov ebx,[binary] ;mov binary to ebx 
    div ebx 
    push edx 
    push formatin 
    call printf 
    add esp,8 
    cmp eax,0  ;compare the quotient with 0; 
    jnz loop 
+0

你應該做一些調試。 – 2014-10-19 09:20:34

回答

1

常見的調用約定是將返回值從函數調用到eax,並且由於printf返回打印的字符數,所以"%d"格式字符串通常總是非零(除非某種類型的輸出失敗)。

所以,通話本身可能會是什麼設置eax爲非零值。

要解決這個問題,你需要在調用printf之前保存eax,然後以後恢復它,通過改變:

push  edx 
push  formatin 
call  printf 
add esp, 8 

到:

push  eax  ; save here 
push  edx 
push  formatin 
call  printf 
add esp, 8 
pop  eax  ; restore here 

這將確保無論printf確實給eax將是無關緊要的,因爲你自己保存和恢復它。

+0

感謝您的幫助! – 23ars 2014-10-19 09:46:26