kern

view src/klibc/stdlib.c @ 91:f83f50c17c3b

continuing with the fs added strtol and strstr to klibc
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 09 Dec 2011 15:29:54 +0200
parents 7e40f14617ed
children
line source
1 #include <stdlib.h>
2 #include <ctype.h>
4 int atoi(const char *str)
5 {
6 return strtol(str, 0, 10);
7 }
9 long atol(const char *str)
10 {
11 return strtol(str, 0, 10);
12 }
14 long strtol(const char *str, char **endp, int base)
15 {
16 long acc = 0;
17 int sign = 1;
19 while(isspace(*str)) str++;
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 }
33 if(*str == '+') {
34 str++;
35 } else if(*str == '-') {
36 sign = -1;
37 str++;
38 }
40 while(*str) {
41 long val;
42 char c = tolower(*str);
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 }
53 acc = acc * base + val;
54 str++;
55 }
57 if(endp) {
58 *endp = (char*)str;
59 }
61 return sign > 0 ? acc : -acc;
62 }
64 void itoa(int val, char *buf, int base)
65 {
66 static char rbuf[16];
67 char *ptr = rbuf;
68 int neg = 0;
70 if(val < 0) {
71 neg = 1;
72 val = -val;
73 }
75 if(val == 0) {
76 *ptr++ = '0';
77 }
79 while(val) {
80 int digit = val % base;
81 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
82 val /= base;
83 }
85 if(neg) {
86 *ptr++ = '-';
87 }
89 ptr--;
91 while(ptr >= rbuf) {
92 *buf++ = *ptr--;
93 }
94 *buf = 0;
95 }
97 void utoa(unsigned int val, char *buf, int base)
98 {
99 static char rbuf[16];
100 char *ptr = rbuf;
102 if(val == 0) {
103 *ptr++ = '0';
104 }
106 while(val) {
107 unsigned int digit = val % base;
108 *ptr++ = digit < 10 ? (digit + '0') : (digit - 10 + 'a');
109 val /= base;
110 }
112 ptr--;
114 while(ptr >= rbuf) {
115 *buf++ = *ptr--;
116 }
117 *buf = 0;
118 }