fe8daf9295cae2ce962edde1819bcaf41653e00f
[lunaix-os.git] / lunaix-os / libs / klibc / stdlib / itoa.c
1 #define __LUNAIX_LIBC
2 #include <stddef.h>
3 #include <klibc/stdlib.h>
4
5 char base_char[] = "0123456789abcdefghijklmnopqrstuvwxyz";
6
7 char*
8 __uitoa_internal(unsigned int value, char* str, int base, unsigned int* size)
9 {
10     unsigned int ptr = 0;
11     do {
12         str[ptr] = base_char[value % base];
13         value = value / base;
14         ptr++;
15     } while (value);
16
17     for (unsigned int i = 0; i < (ptr >> 1); i++) {
18         char c = str[i];
19         str[i] = str[ptr - i - 1];
20         str[ptr - i - 1] = c;
21     }
22     str[ptr] = '\0';
23     if (size) {
24         *size = ptr;
25     }
26     return str;
27 }
28
29 char*
30 __itoa_internal(int value, char* str, int base, unsigned int* size)
31 {
32     if (value < 0 && base == 10) {
33         str[0] = '-';
34         unsigned int _v = (unsigned int)(-value);
35         __uitoa_internal(_v, str + 1, base, size);
36     } else {
37         __uitoa_internal(value, str, base, size);
38     }
39
40     return str;
41 }
42
43 char*
44 itoa(int value, char* str, int base)
45 {
46     return __itoa_internal(value, str, base, NULL);
47 }