C Programming/stdlib.h/itoa

From Wikibooks, open books for an open world
Jump to navigation Jump to search

The itoa (integer to ASCII) 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 <stdlib.h> while in non-conforming mode, because it is a logical counterpart to the standard library function atoi.

void itoa(int input, char *buffer, int radix)

itoa takes the integer input value input and converts it to a number in base radix. The resulting number (a sequence of base-radix digits) is written to the output buffer buffer.

Depending on the implementation, itoa may return a pointer to the first character in buffer, or may be designed so that passing a null buffer causes the function to return the length of the string that would have been written into a valid buffer.

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[edit | edit source]

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 of itoa, on page 64 [for Spanish editions go to page 47]. The book notes several issues with this implementation, including the fact that it does not correctly handle the most negative number −2wordsize-1.[1]

 /* 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] = '\0';

The function reverse used above is implemented two pages earlier:

 #include <string.h>
 /* reverse:  reverse string s in place */
 void reverse(char s[])
     int i, j;
     char c;
     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;

Other appearances[edit | edit source]

An itoa function (and a similar function, ftoa, that converted a float to a string) was listed in the first-edition Unix manual.[2] Unlike the versions given above, the Unix library version had an interface roughly equivalent to

void itoa(int input, void (*subr)(char))

and would invoke the callback routine subr on each character in the output string, thus eliminating the need for a buffer big enough to hold the entire string.

References[edit | edit source]

  1. For the solution to this exercise, see "K&R2 solutions" on clc-wiki.net.
  2. "Unix Programmer's Manual", November 3, 1971. Section "Library routines".

External links[edit | edit source]