Implement your own itoa()

This blog post will teach you how to Implement your own itoa() function in C. The itoa() function is a non-standard function that converts an integer into a null-terminated string. I have already written a blog post on how to convert an integer to a string if you want you can check, an efficient way to convert an int to a string.

Now let’s see the implementation of itoa in C. But before writing an example code I want to suggest that you should use the standard library function because they have a very efficient and tailored implementation of the itoa() function.

#include<stdio.h>

//function to reverse a string
void reverse(char str[], int length)
{
    int start;
    int end = length -1;

    for(start = 0; start < end; ++start, --end)
    {
        const char ch = str[start];
        str[start] = str[end];
        str[end] = ch;
    }

}

//Implemented own itoa function
char* itoa(int num, char* str, int base)
{
    int i = 0;
    char isNegNum = 0;

    /*Handle 0 explicitly, 
      otherwise empty string is printed for 0 */
    if (num == 0)
    {
        str[i++] = '0';
        str[i] = '\0';
    }
    else
    {
        // In library itoa function -ve numbers handled only with
        // base 10. SO here we are also following same concept
        if ((num < 0) && (base == 10))
        {
            isNegNum = 1;
            num = -num; // make num positive
        }
        // Process individual digits
        do
        {
            const int rem = (num % base);
            str[i++] = (rem > 9)? ((rem-10) + 'a') : (rem + '0');
            num = num/base;
        }
        while (num != 0);

        // If number is negative, append '-'
        if (isNegNum)
        {
            str[i++] = '-';
        }

        // Append string terminator
        str[i] = '\0';

        // Reverse the string
        reverse(str, i);
    }

    return str;
}


int main()
{
    char str[100] = {0};
    
    printf("Base:10 %s\n", itoa(2324, str, 10));
    printf("Base:10 %s\n", itoa(-2324, str, 10));
    printf("Base:16 %s\n", itoa(2324, str, 16));
    printf("Base:8 %s\n", itoa(2324, str, 8));
    printf("Base:2 %s\n", itoa(2324, str, 2));
    
    return 0;
}

Output:

Base:10 2324
Base:10 -2324
Base:16 914
Base:8 4424
Base:2 100100010100

 

Recommended Post: