clinuxembedded

Want to Convert Integer to String without itoa function


i want to convert int to char* in C without using itoa() function.

Because on my Linux Systems i itoa function is not there. i am using this code which i found from here

I want to run this function on Embedded devices also which are using Linux.

So i am looking for without use of itoa.

I dnt want to use sprintf also because its uses for just prints.

So any body please help me to figured out this problem.

Thanks


Solution

  • I found solution regarding this..

    I am Happy to and i want which i expected.

    #include <string.h>
    #include <stdlib.h>
    
    char *i_to_a(int num);
    
    int main()
    {
    
        char *str = i_to_a(4567);
        printf("%s",str);
        free(str);
        str = NULL;
    return 0;
    
    }
    int no_of_digits(int num)
    {
        int digit_count = 0;
    
        while(num > 0)
        {
            digit_count++;
            num /= 10;
        }
    
        return digit_count;
    }
    
    
    char *i_to_a(int num)
    {
        char *str;
        int digit_count = 0;
    
        if(num < 0)
        {
            num = -1*num;
            digit_count++;
        }
    
        digit_count += no_of_digits(num);   
        str = malloc(sizeof(char)*(digit_count+1));
    
        str[digit_count] = '\0';
    
        while(num > 0)
        {
            str[digit_count-1] = num%10 + '0';
            num = num/10;
            digit_count--;
        }
    
        if(digit_count == 1)
            str[0] = '-';
    
        return str;
    }