Implement your own itoa() in C

In C programming, the itoa() function converts an integer to a string representation. However, itoa() is not part of the C standard library. Here we'll implement our own version using both the sprintf() approach and a manual conversion method.

Syntax

char* itoa(int value, char* str, int base);

Method 1: Using sprintf()

The sprintf() function formats and stores data in a string buffer instead of printing to console −

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

char* my_itoa_sprintf(int number, char* str) {
    sprintf(str, "%d", number);
    return str;
}

int main() {
    int number = 42;
    char str[20];
    
    printf("Number: %d<br>", number);
    printf("String: %s<br>", my_itoa_sprintf(number, str));
    return 0;
}
Number: 42
String: 42

Method 2: Manual Conversion

This approach manually extracts digits and builds the string without using sprintf()

#include <stdio.h>
#include <string.h>

char* my_itoa_manual(int num, char* str) {
    int i = 0;
    int isNegative = 0;
    
    /* Handle negative numbers */
    if (num < 0) {
        isNegative = 1;
        num = -num;
    }
    
    /* Handle 0 explicitly */
    if (num == 0) {
        str[i++] = '0';
        str[i] = '\0';
        return str;
    }
    
    /* Extract digits in reverse order */
    while (num != 0) {
        int rem = num % 10;
        str[i++] = rem + '0';
        num = num / 10;
    }
    
    /* Add negative sign if needed */
    if (isNegative) {
        str[i++] = '-';
    }
    
    str[i] = '\0';
    
    /* Reverse the string */
    int start = 0;
    int end = i - 1;
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
    
    return str;
}

int main() {
    char str[20];
    int numbers[] = {123, -456, 0, 789};
    int size = sizeof(numbers) / sizeof(numbers[0]);
    
    for (int i = 0; i < size; i++) {
        printf("Number: %d, String: %s<br>", numbers[i], my_itoa_manual(numbers[i], str));
    }
    return 0;
}
Number: 123, String: 123
Number: -456, String: -456
Number: 0, String: 0
Number: 789, String: 789

Comparison

Method Pros Cons Time Complexity
sprintf() Simple, concise Uses library function O(log n)
Manual No library dependency, educational More complex code O(log n)

Key Points

  • Always ensure the destination buffer is large enough to hold the result
  • Handle negative numbers and zero as special cases
  • The manual method requires string reversal after digit extraction

Conclusion

Both methods effectively convert integers to strings. The sprintf() approach is simpler for practical use, while the manual method provides better understanding of the conversion process and avoids library dependencies.

Updated on: 2026-03-15T10:15:29+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements