forked from aligrudi/neatlibc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atoi.c
125 lines (120 loc) · 2.13 KB
/
atoi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#include <errno.h>
int atoi(char *s)
{
int num = 0;
int neg = 0;
while (isspace(*s))
s++;
if (*s == '-' || *s == '+')
neg = *s++ == '-';
while ((unsigned) (*s - '0') <= 9u)
num = num * 10 + *s++ - '0';
return neg ? -num : num;
}
long atol(char *s)
{
long num = 0;
int neg = 0;
while (isspace(*s))
s++;
if (*s == '-' || *s == '+')
neg = *s++ == '-';
while ((unsigned) (*s - '0') <= 9u)
num = num * 10 + *s++ - '0';
return neg ? -num : num;
}
static int digit(char c, int base)
{
int d;
if (c <= '9') {
d = c - '0';
} else if (c <= 'Z') {
d = 10 + c - 'A';
} else {
d = 10 + c - 'a';
}
return d < base ? d : -1;
}
long strtol(const char *s, char **endptr, int base)
{
int sgn = 1;
int overflow = 0;
long num;
int dig;
while (isspace(*s))
s++;
if (*s == '-' || *s == '+')
sgn = ',' - *s++;
if (base == 0) {
if (*s == '0') {
if (s[1] == 'x' || s[1] == 'X')
base = 16;
else
base = 8;
} else {
base = 10;
}
}
if (base == 16 && *s == '0' && (s[1] == 'x' || s[1] == 'X'))
s += 2;
for (num = 0; (dig = digit(*s, base)) >= 0; s++) {
if (num > LONG_MAX / base)
overflow = 1;
num *= base;
if (num > LONG_MAX - dig)
overflow = 1;
num += dig;
}
if (endptr)
*endptr = s;
if (overflow) {
num = sgn > 0 ? LONG_MAX : LONG_MIN;
errno = ERANGE;
} else {
num *= sgn;
}
return num;
}
unsigned long strtoul(const char *s, char **endptr, int base)
{
int sgn = 1;
int overflow = 0;
unsigned long num;
int dig;
while (isspace(*s))
s++;
if (*s == '-' || *s == '+')
sgn = ',' - *s++;
if (base == 0) {
if (*s == '0') {
if (s[1] == 'x' || s[1] == 'X')
base = 16;
else
base = 8;
} else {
base = 10;
}
}
if (base == 16 && *s == '0' && (s[1] == 'x' || s[1] == 'X'))
s += 2;
for (num = 0; (dig = digit(*s, base)) >= 0; s++) {
if (num > (unsigned long) ULONG_MAX / base)
overflow = 1;
num *= base;
if (num > (unsigned long) ULONG_MAX - dig)
overflow = 1;
num += dig;
}
if (endptr)
*endptr = s;
if (overflow) {
num = ULONG_MAX;
errno = ERANGE;
} else {
num *= sgn;
}
return num;
}