</>EmbeddedInterview

How do you implement atoi() and itoa() in C?

MediumArrays & Strings (Coding Round)

Short answer: atoi: skip leading spaces, read an optional sign, then for each digit compute value = value * 10 + (c - '0'), checking for overflow before multiplying; stop at the first non-digit. itoa: repeatedly take value % base as the next digit (from the least significant end) and divide by the base, then reverse the digits; handle zero and negative numbers (including INT_MIN) carefully.

#include <ctype.h>
#include <limits.h>
#include <stdbool.h>

/* returns false on overflow or if there are no digits */
bool my_atoi(const char *s, int *out)
{
    while (isspace((unsigned char)*s)) s++;
    bool neg = false;
    if (*s == '+' || *s == '-') neg = (*s++ == '-');
    if (!isdigit((unsigned char)*s)) return false;

    unsigned limit = neg ? (unsigned)INT_MAX + 1u : (unsigned)INT_MAX;
    unsigned v = 0;
    while (isdigit((unsigned char)*s)) {
        unsigned d = (unsigned)(*s++ - '0');
        if (v > (limit - d) / 10u) return false;     /* v * 10 + d would exceed limit */
        v = v * 10u + d;
    }
    *out = neg ? (int)(0u - v) : (int)v;             /* well-defined for INT_MIN on two's complement */
    return true;
}

/* buf needs at least 34 bytes for base 2; base 2..16 */
char *my_itoa(int value, char *buf, unsigned base)
{
    static const char digits[] = "0123456789abcdef";
    unsigned u = (value < 0 && base == 10) ? 0u - (unsigned)value : (unsigned)value;
    char *p = buf;
    do {                                   /* do-while: value 0 still prints "0" */
        *p++ = digits[u % base];
        u /= base;
    } while (u);
    if (value < 0 && base == 10) *p++ = '-';
    *p = '\0';
    for (char *l = buf, *r = p - 1; l < r; l++, r--) {   /* reverse in place */
        char t = *l; *l = *r; *r = t;
    }
    return buf;
}
/* my_atoi("  -42abc") -> -42, my_itoa(-2147483648, buf, 10) -> "-2147483648" */

Edge cases interviewers test: leading spaces, "+" or "-" alone, "42abc" (stop at the first non-digit), overflow ("99999999999"), INT_MIN (its absolute value does not fit in int, which is why the conversion uses unsigned), and 0.

Why not the standard functions? atoi() has no error reporting (overflow is undefined behaviour); use strtol() and check errno and the end pointer. itoa() is not standard C at all; use snprintf(). On small MCUs, printf-family code can cost several KB of flash, which is why hand-written conversion routines are common.

Embedded follow-up: converting a 32-bit value to decimal on a Cortex-M0 (no divide instruction) — the repeated / 10 becomes a library call. A multiply-by-reciprocal trick ((x * 0xCCCCCCCDull) >> 35 for division by 10) is what compilers generate on cores with a fast multiplier.