2012-02-05 103 views
2

有一個關於NASM中整數到字符串轉換的問題。NASM - 整數到字符串

我的問題是如何連接數字,使輸出包含循環終止時的所有數字,而不是最後計算的數字?

例如, 1234 - > 1234 DIV 10 =剩餘4 =>緩衝= 「4」 123 - > 123 DIV 10 =剩餘3 =>緩衝= 「3」 等等

我的程序只是存儲計算的最後一位數字('1')並打印。

這裏是我的代碼文件:

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    int i; 
    char *str; 
    printf("Enter a number: "); 
    scanf ("%d", &i); 
    str=int2string(i); 
    printf("Number as string is: %s\n", str); 

    return 0; 
} 

%include "asm_io.inc" 

segment .data 

segment .bss 
buffer db 20 ; buffer of size 8 bits (in reference to c file) 

segment .text 
    global int2string 
int2string: 
     enter 0,0    ; setup routine 
     pusha 
    mov esi, 0  ; set sign to 0 
    mov ebx, 0  ; set current remainder to 0 
    mov edi, 0  ; set the current digit in eax 

     mov eax, [ebp+8]  ; eax contains input value of int2string 

    jmp placeValues 

placeValues: 
    mov edx, 0  ; set remainder to 0 
    mov eax, eax  ; redundancy ensures dividend is eax 
    mov ebx, 10  ; sets the divisor to value of 10 
    div ebx   ; eax = eax/ebx 

    mov ebx, 48  ; set ebx to 48 for ASCII conversion 
    add ebx, edx  ; add remainder to ebx for ASCII value 
    add dword[buffer], ebx ; store the number in the buffer 

    cmp eax, 0 
    jz return 
    jmp placeValues 

return: 
    popa 
    mov eax, buffer  ; move buffer value to eax 
     leave      
     ret 
+0

那麼+ int的數字計數不能超過10,那麼您可以爲10個字符分配空間,並在填充數字並返回數組的基數時遞增循環內的賦值索引? – 2012-02-05 05:56:11

+0

完美運行,感謝您的快速響應 – user1074249 2012-02-05 06:00:48

回答

1

嗯,+ INT數字計數不能十更長的時間,所以你可以分配房間十個字符和環路內遞增分配索引你填充數字並返回數組的基數?

- 我不是很有信心,這是你需要的,所以我把它作爲一個評論,但因爲它而且你是新的,我應該真的把它移動到這裏,作爲一個正式的答案。