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 #define _DEFAULT_SOURCE
30 #include <stdlib.h>
31 
32 char *
__utoa(unsigned value,char * str,int base)33 __utoa (unsigned value,
34         char *str,
35         int base)
36 {
37   const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
38   int i, j;
39   unsigned remainder;
40   char c;
41 
42   /* Check base is supported. */
43   if ((base < 2) || (base > 36))
44     {
45       str[0] = '\0';
46       return NULL;
47     }
48 
49   /* Convert to string. Digits are in reverse order.  */
50   i = 0;
51   do
52     {
53       remainder = value % base;
54       str[i++] = digits[remainder];
55       value = value / base;
56     } while (value != 0);
57   str[i] = '\0';
58 
59   /* Reverse string.  */
60   for (j = 0, i--; j < i; j++, i--)
61     {
62       c = str[j];
63       str[j] = str[i];
64       str[i] = c;
65     }
66 
67   return str;
68 }
69 
70 char *
utoa(unsigned value,char * str,int base)71 utoa (unsigned value,
72         char *str,
73         int base)
74 {
75   return __utoa (value, str, base);
76 }
77