Partial merge of condrv_restructure branch r65657.
[reactos.git] / reactos / lib / sdk / crt / string / strtoul.c
1 #include <precomp.h>
2 #include <ctype.h>
3
4 /*
5 * Convert a string to an unsigned long integer.
6 *
7 * Ignores `locale' stuff. Assumes that the upper and lower case
8 * alphabets and digits are each contiguous.
9 *
10 * @implemented
11 */
12 unsigned long
13 strtoul(const char *nptr, char **endptr, int base)
14 {
15 const char *s = nptr;
16 unsigned long acc;
17 int c;
18 unsigned long cutoff;
19 int neg = 0, any, cutlim;
20
21 /*
22 * See strtol for comments as to the logic used.
23 */
24 do {
25 c = *s++;
26 } while (isspace(c));
27 if (c == '-')
28 {
29 neg = 1;
30 c = *s++;
31 }
32 else if (c == '+')
33 c = *s++;
34 if ((base == 0 || base == 16) &&
35 c == '0' && (*s == 'x' || *s == 'X'))
36 {
37 c = s[1];
38 s += 2;
39 base = 16;
40 }
41 if (base == 0)
42 base = c == '0' ? 8 : 10;
43 cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
44 cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
45 for (acc = 0, any = 0;; c = *s++)
46 {
47 if (isdigit(c))
48 c -= '0';
49 else if (isalpha(c))
50 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
51 else
52 break;
53 if (c >= base)
54 break;
55 if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
56 any = -1;
57 else {
58 any = 1;
59 acc *= base;
60 acc += c;
61 }
62 }
63 if (any < 0)
64 {
65 acc = ULONG_MAX;
66 #ifndef _LIBCNT_
67 _set_errno(ERANGE);
68 #endif
69 }
70 else if (neg)
71 acc = 0-acc;
72 if (endptr != 0)
73 *endptr = any ? (char *)((size_t)(s - 1)) : (char *)((size_t)nptr);
74 return acc;
75 }