ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-252 min read

Convert integers to character strings in standard C without non-standard itoa. Full working code for arbitrary bases, signs, and buffer safety.

Why Implement itoa in ISO C?

itoa() is a legacy non-standard function provided in old Turbo C or Windows CRT compilers, but is not part of standard ISO C99, C11, or C23. Writing an in-place itoa() is a common systems interview question.


C Source Code

c (ISO Standard)
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

void reverseSubstr(char *str, int length) {
    int start = 0;
    int end = length - 1;
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}

char* customItoa(int num, char *buffer, int base) {
    if (base < 2 || base > 36) {
        buffer[0] = '\0';
        return buffer;
    }

    int i = 0;
    bool isNegative = false;

    if (num == 0) {
        buffer[i++] = '0';
        buffer[i] = '\0';
        return buffer;
    }

    if (num < 0 && base == 10) {
        isNegative = true;
        num = -num;
    }

    while (num != 0) {
        int rem = num % base;
        buffer[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
        num /= base;
    }

    if (isNegative) {
        buffer[i++] = '-';
    }

    buffer[i] = '\0';
    reverseSubstr(buffer, i);
    return buffer;
}

int main() {
    char buf[32];
    int values[] = {1234, -567, 255, 0};

    printf("Integer to String Conversions:\n\n");
    for (int i = 0; i < 4; i++) {
        int val = values[i];
        printf("  Decimal: %d -> Str: \"%s\"\n", val, customItoa(val, buf, 10));
    }
    printf("  Hex: 255 -> Base 16 Str: \"%s\"\n", customItoa(255, buf, 16));

    return 0;
}

Sample Output

text (ISO Standard)
Integer to String Conversions:

  Decimal: 1234 -> Str: "1234"
  Decimal: -567 -> Str: "-567"
  Decimal: 255 -> Str: "255"
  Decimal: 0 -> Str: "0"
  Hex: 255 -> Base 16 Str: "ff"

Complexity Analysis

  • Time Complexity: $O(\log_{base} n)$ digit extractions.
  • Space Complexity: O(1) writes directly into caller-provided buffer.

Related C Examples & Tutorials