Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NASM - Integer to String

Tags:

x86

nasm

have a question regarding integer to string conversion in NASM.

My question is how do I concatenate the digits such that the output contains all the digits when the loop is terminated, rather than the last calculated digit?

Eg. 1234 -> 1234 div 10 = remainder 4 => Buffer = "4" 123 -> 123 div 10 = remainder 3 => Buffer = "3" etc...

My program just stores the last digit calculated ('1') and prints that.

Here are my code files:

#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
like image 667
user1074249 Avatar asked Apr 11 '26 01:04

user1074249


1 Answers

Well, the digit count for +int can't be longer than ten, so could you allocate room for ten chars and increment the assignment index within the loop as you fill digits and return the base of the array?

-- I wasn't very confident that this was all you needed so I put it as a comment, but since it was and as you are new, I should really move it here, as an official answer.

like image 55
Jason Kleban Avatar answered Apr 15 '26 05:04

Jason Kleban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!