25bd15a151e9f5c64a27d89fc106c2c71684762a
[reactos.git] / reactos / lib / sdk / crt / string / strtol.c
1 #include <precomp.h>
2
3 /*
4 * @implemented
5 */
6 long
7 strtol(const char *nptr, char **endptr, int base)
8 {
9 const char *s = nptr;
10 unsigned long acc;
11 int c;
12 unsigned long cutoff;
13 int neg = 0, any, cutlim;
14
15 /*
16 * Skip white space and pick up leading +/- sign if any.
17 * If base is 0, allow 0x for hex and 0 for octal, else
18 * assume decimal; if base is already 16, allow 0x.
19 */
20 do {
21 c = *s++;
22 } while (isspace(c));
23 if (c == '-')
24 {
25 neg = 1;
26 c = *s++;
27 }
28 else if (c == '+')
29 c = *s++;
30 if ((base == 0 || base == 16) &&
31 c == '0' && (*s == 'x' || *s == 'X'))
32 {
33 c = s[1];
34 s += 2;
35 base = 16;
36 }
37 if (base == 0)
38 base = c == '0' ? 8 : 10;
39
40 /*
41 * Compute the cutoff value between legal numbers and illegal
42 * numbers. That is the largest legal value, divided by the
43 * base. An input number that is greater than this value, if
44 * followed by a legal input character, is too big. One that
45 * is equal to this value may be valid or not; the limit
46 * between valid and invalid numbers is then based on the last
47 * digit. For instance, if the range for longs is
48 * [-2147483648..2147483647] and the input base is 10,
49 * cutoff will be set to 214748364 and cutlim to either
50 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
51 * a value > 214748364, or equal but the next digit is > 7 (or 8),
52 * the number is too big, and we will return a range error.
53 *
54 * Set any if any `digits' consumed; make it negative to indicate
55 * overflow.
56 */
57 cutoff = neg ? ((unsigned long)LONG_MAX+1) : LONG_MAX;
58 cutlim = cutoff % (unsigned long)base;
59 cutoff /= (unsigned long)base;
60 for (acc = 0, any = 0;; c = *s++)
61 {
62 if (isdigit(c))
63 c -= '0';
64 else if (isalpha(c))
65 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
66 else
67 break;
68 if (c >= base)
69 break;
70 if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
71 any = -1;
72 else
73 {
74 any = 1;
75 acc *= base;
76 acc += c;
77 }
78 }
79 if (any < 0)
80 {
81 acc = neg ? LONG_MIN : LONG_MAX;
82 #ifndef _LIBCNT_
83 _set_errno(ERANGE);
84 #endif
85 }
86 else if (neg)
87 acc = 0-acc;
88 if (endptr != 0)
89 *endptr = any ? (char *)((size_t)(s - 1)) : (char *)((size_t)nptr);
90 return acc;
91 }