- Itoa
The itoa function is a widespread non-standard extension to the standard C programming language. It cannot be portably used, as it is not defined in any of the C language standards; however, compilers often provide it through the header
<
while in non-conforming mode, because it is a logical counterpart to the standard library functionstdlib.h >
.atoi :
void itoa(int input, char *buffer, int radix)
itoa
takes the integer input valueinput
and converts it to a number in baseradix
. The resulting number (a sequence of base-radix
digits) is written to the output bufferbuffer
.Depending on the implementation,
itoa
may return a pointer to the first character inbuffer
, or may be designed so that passing a nullbuffer
causes the function to return the length of the string that "would have" been written into a validbuffer
.For converting a number to a string in base 8 (octal), 10 (decimal), or 16 (
hexadecimal ), a Standard-compliant alternative is to use the standard library function
.sprintf K&R implementation
The function
itoa
appeared in the first edition of Kernighan and Ritchie's "The C Programming Language", on page 60. The second edition of "The C Programming Language" ("K&R2") contains the following implementation ofitoa
, on page 64. The book notes several issues with this implementation, including the fact that it does not correctly handle the most negative number −2wordsize-1. [For the solution to this exercise, see [http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_3:Exercise_4 "K&R2 solutions"] on "clc-wiki.net".]/* itoa: convert n to characters in s */ void itoa(int n, char s [] ) { int i, sign; if ((sign = n) < 0) /* record sign */ n = -n; /* make n positive */ i = 0; do { /* generate digits in reverse order */ s [i++] = n % 10 + '0'; /* get next digit */ } while ((n /= 10) > 0); /* delete it */ if (sign < 0) s [i++] = '-'; s [i] = '
Wikimedia Foundation. 2010.