1 /* Copyright (c) 2014 Corinna Vinschen <corinna@vinschen.de> */
2 /*
3 FUNCTION
4 <<itoa>>---integer to string
5 
6 INDEX
7 	itoa
8 
9 SYNOPSIS
10 	#include <stdlib.h>
11 	char *itoa(int <[value]>, char *<[str]>, int <[base]>);
12 	char *__itoa(int <[value]>, char *<[str]>, int <[base]>);
13 
14 DESCRIPTION
15 <<itoa>> converts the integer <[value]> to a null-terminated string
16 using the specified base, which must be between 2 and 36, inclusive.
17 If <[base]> is 10, <[value]> is treated as signed and the string will be
18 prefixed with '-' if negative. For all other bases, <[value]> is treated as
19 unsigned. <[str]> should be an array long enough to contain the converted
20 value, which in the worst case is sizeof(int)*8+1 bytes.
21 
22 RETURNS
23 A pointer to the string, <[str]>, or NULL if <[base]> is invalid.
24 
25 PORTABILITY
26 <<itoa>> is non-ANSI.
27 
28 No supporting OS subroutine calls are required.
29 */
30 
31 #define _DEFAULT_SOURCE
32 #include <stdlib.h>
33 
34 char *
__itoa(int value,char * str,int base)35 __itoa (int value,
36         char *str,
37         int base)
38 {
39   unsigned uvalue;
40   int i = 0;
41 
42   /* Check base is supported. */
43   if ((base < 2) || (base > 36))
44     {
45       str[0] = '\0';
46       return NULL;
47     }
48 
49   /* Negative numbers are only supported for decimal.
50    * Cast to unsigned to avoid overflow for maximum negative value.  */
51   if ((base == 10) && (value < 0))
52     {
53       str[i++] = '-';
54       uvalue = (unsigned)-value;
55     }
56   else
57     uvalue = (unsigned)value;
58 
59   __utoa (uvalue, &str[i], base);
60   return str;
61 }
62 
63 char *
itoa(int value,char * str,int base)64 itoa (int value,
65         char *str,
66         int base)
67 {
68   return __itoa (value, str, base);
69 }
70