1 /* Copyright (c) 2014 Corinna Vinschen <corinna@vinschen.de> */
2 /*
3 FUNCTION
4 <<utoa>>---unsigned integer to string
5 
6 INDEX
7 	utoa
8 
9 SYNOPSIS
10 	#include <stdlib.h>
11 	char *utoa(unsigned <[value]>, char *<[str]>, int <[base]>);
12 	char *__utoa(unsigned <[value]>, char *<[str]>, int <[base]>);
13 
14 DESCRIPTION
15 <<utoa>> converts the unsigned integer [<value>] to a null-terminated string
16 using the specified base, which must be between 2 and 36, inclusive.
17 <[str]> should be an array long enough to contain the converted
18 value, which in the worst case is sizeof(int)*8+1 bytes.
19 
20 RETURNS
21 A pointer to the string, <[str]>, or NULL if <[base]> is invalid.
22 
23 PORTABILITY
24 <<utoa>> is non-ANSI.
25 
26 No supporting OS subroutine calls are required.
27 */
28 
29 #include <stdlib.h>
30 
31 char *
__utoa(unsigned value,char * str,int base)32 __utoa (unsigned value,
33         char *str,
34         int base)
35 {
36   const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
37   int i, j;
38   unsigned remainder;
39   char c;
40 
41   /* Check base is supported. */
42   if ((base < 2) || (base > 36))
43     {
44       str[0] = '\0';
45       return NULL;
46     }
47 
48   /* Convert to string. Digits are in reverse order.  */
49   i = 0;
50   do
51     {
52       remainder = value % base;
53       str[i++] = digits[remainder];
54       value = value / base;
55     } while (value != 0);
56   str[i] = '\0';
57 
58   /* Reverse string.  */
59   for (j = 0, i--; j < i; j++, i--)
60     {
61       c = str[j];
62       str[j] = str[i];
63       str[i] = c;
64     }
65 
66   return str;
67 }
68 
69 char *
utoa(unsigned value,char * str,int base)70 utoa (unsigned value,
71         char *str,
72         int base)
73 {
74   return __utoa (value, str, base);
75 }
76