Implementing the itoa() function in C / C++

Filed Under: C Programming
Itoa C Cpp

In this article, we’ll take a look at implementing the itoa() function in C/C++.

This is a useful utility function which converts an integer into a null-terminated string.

However, it isn’t supported natively by most compilers, as it is not a part of the C standard.

Therefore, let’s take a look at using this function, by implementing it ourselves!.

Basic Syntax of the itoa() function in C/C++

While this function may be available in some compilers, there is no function as such, in most of them.

The itoa() function takes in an integer num, and stores it into buffer. It also has an optional parameter base, which converts it into the appropriate base.

By default, base is set to 10 (decimal base).

After populating buffer, it returns a pointer to the first character of buffer, if the conversion is successful. Otherwise, it returns NULL.

char* itoa(int num, char* buffer, int base)

Since there isn’t any default itoa() function in most common C compilers, let’s implement it!


Implementing the itoa() function in C / C++

We’ll take a number, and convert it to a string. We’ll consider both positive and negative integers, and see how itoa() handles them.

Although some websites may have implemented itoa() by evaluating the digits from right to left and then reversing the string, we’ll use a different approach. t

We’ll evaluate the digits from left to right, with the help of certain function from the <math.h> library.

We’ll follow the below procedure:

  • Find the number of digits of num. If num is positive, we know that the number of digits will be floor(log(num, base)) + 1. (Hint: This is pretty easy to derive using logarithms).
  • If num is negative, we will only consider the case where base = 10, since we may need to use separate algorithms to evaluate for any base. We need to put the minus sign as the first digit!
  • Start from the leftmost (highest) digit of num, and keep adding the value to the buffer.

The complete program is shown below. You may be able to understand this better by reading through the code!

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

char* itoa(int num, char* buffer, int base) {
    int curr = 0;

    if (num == 0) {
        // Base case
        buffer[curr++] = '0';
        buffer[curr] = '\0';
        return buffer;
    }

    int num_digits = 0;

    if (num < 0) {
        if (base == 10) {
            num_digits ++;
            buffer[curr] = '-';
            curr ++;
            // Make it positive and finally add the minus sign
            num *= -1;
        }
        else
            // Unsupported base. Return NULL
            return NULL;
    }

    num_digits += (int)floor(log(num) / log(base)) + 1;

    // Go through the digits one by one
    // from left to right
    while (curr < num_digits) {
        // Get the base value. For example, 10^2 = 1000, for the third digit
        int base_val = (int) pow(base, num_digits-1-curr);

        // Get the numerical value
        int num_val = num / base_val;

        char value = num_val + '0';
        buffer[curr] = value;

        curr ++;
        num -= base_val * num_val;
    }
    buffer[curr] = '\0';
    return buffer;
}

int main() {
    int a = 1234;
    char buffer[256];
    if (itoa(a, buffer, 10) != NULL) {
        printf("Input = %d, base = %d, Buffer = %s\n", a, 10, buffer);
    }
    int b = -231;
    if (itoa(b, buffer, 10) != NULL) {
        printf("Input = %d, base = %d, Buffer = %s\n", b, 10, buffer);
    }
    int c = 10;
    if (itoa(c, buffer, 2) != NULL) {
        printf("Input = %d, base = %d, Buffer = %s\n", c, 2, buffer);
    }
    return 0;
}

Output

Input = 1234, base = 10, Buffer = 1234
Input = -231, base = 10, Buffer = -231
Input = 10, base = 2, Buffer = 1010

NOTE: If you’re compiling with gcc, use the -lm flag to include the math library.

gcc -o test.out test.c -lm

Indeed, we were able to get it working. Not only did this work for integers, but only for other bases too!


Conclusion

Hopefully you were able to get an understanding to converting integers to strings using itoa(), and possibly even implemented one yourself, using this guide!

For similar content, do go through our tutorial section on C programming


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages