brought the code over from the amiga test
[lugburz] / src / amiga / libc / stdlib.c
1 #include <stdlib.h>
2 #include <ctype.h>
3
4 int atoi(const char *str)
5 {
6         return strtol(str, 0, 10);
7 }
8
9 long atol(const char *str)
10 {
11         return strtol(str, 0, 10);
12 }
13
14 long strtol(const char *str, char **endp, int base)
15 {
16         long acc = 0;
17         int sign = 1;
18
19         while(isspace(*str)) str++;
20
21         if(base == 0) {
22                 if(str[0] == '0') {
23                         if(str[1] == 'x' || str[1] == 'X') {
24                                 base = 16;
25                         } else {
26                                 base = 8;
27                         }
28                 } else {
29                         base = 10;
30                 }
31         }
32
33         if(*str == '+') {
34                 str++;
35         } else if(*str == '-') {
36                 sign = -1;
37                 str++;
38         }
39
40         while(*str) {
41                 long val;
42                 char c = tolower(*str);
43
44                 if(isdigit(c)) {
45                         val = *str - '0';
46                 } else if(c >= 'a' || c <= 'f') {
47                         val = 10 + c - 'a';
48                 }
49                 if(val >= base) {
50                         break;
51                 }
52
53                 acc = acc * base + val;
54                 str++;
55         }
56
57         if(endp) {
58                 *endp = (char*)str;
59         }
60
61         return sign > 0 ? acc : -acc;
62 }
63
64 void itoa(int val, char *buf, int base)
65 {
66         static char rbuf[16];
67         char *ptr = rbuf;
68         int neg = 0;
69
70         if(val < 0) {
71                 neg = 1;
72                 val = -val;
73         }
74
75         if(val == 0) {
76                 *ptr++ = '0';
77         }
78
79         while(val) {
80                 int digit = val % base;
81                 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
82                 val /= base;
83         }
84
85         if(neg) {
86                 *ptr++ = '-';
87         }
88
89         ptr--;
90
91         while(ptr >= rbuf) {
92                 *buf++ = *ptr--;
93         }
94         *buf = 0;
95 }
96
97 void utoa(unsigned int val, char *buf, int base)
98 {
99         static char rbuf[16];
100         char *ptr = rbuf;
101
102         if(val == 0) {
103                 *ptr++ = '0';
104         }
105
106         while(val) {
107                 unsigned int digit = val % base;
108                 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
109                 val /= base;
110         }
111
112         ptr--;
113
114         while(ptr >= rbuf) {
115                 *buf++ = *ptr--;
116         }
117         *buf = 0;
118 }
119