basics · intermediate · ~25 min

Convert int to string in a fixed buffer

Build digits in reverse, then reverse.

Challenge

Convert an integer to its decimal text form inside a caller-provided buffer — the inverse of atoi.

Task

Implement int itoa_buf(int n, char *buf, size_t cap) that writes the decimal representation of n into buf as a NUL-terminated string. Return the number of characters written (not counting the NUL), or -1 if buf (capacity cap) is too small to hold the digits plus the terminator.

Input

An int n, a destination buffer buf, and its capacity size_t cap (>= 1).

Output

Returns the length of the written string (excluding the NUL) on success, or -1 if it would not fit.

Example

itoa_buf(42, buf, 32)        ->   2,   buf == "42"
itoa_buf(-7, buf, 32)        ->   2,   buf == "-7"
itoa_buf(0, buf, 32)         ->   1,   buf == "0"
itoa_buf(INT_MIN, buf, 32)   ->   11,  buf == "-2147483648"
itoa_buf(1234, buf, 3)       ->   -1   (doesn't fit)

Edge cases

  • n == 0 writes "0" (length 1).
  • INT_MIN: its magnitude is one larger than INT_MAX, so negate via unsigned.
  • The minus sign counts toward the length and the capacity.

Rules

  • Do not call sprintf/snprintf — build the digits with plain arithmetic.

Why this matters

Building a string from an integer is the inverse of atoi and crops up in every printf-without-printf scenario (kernel logging, embedded firmware, etc.).

Input format

An int n, a buffer buf, and its capacity size_t cap (>= 1).

Output format

Number of chars written (excluding NUL), or -1 if it doesn't fit.

Constraints

No sprintf; plain arithmetic. Handle 0 and INT_MIN. NUL and '-' count toward cap.

Starter code

#include <stddef.h>
int itoa_buf(int n, char *buf, size_t cap) { /* TODO */ return -1; }

Common mistakes

-n overflows on INT_MIN; not handling zero (loop never runs); writing past the buffer.

Edge cases to handle

n == 0 writes "0". n == INT_MIN — magnitude is one bigger than INT_MAX.

Complexity

O(digit count).

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.