1 /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
3 #include <msvcrt/ctype.h>
4 #include <msvcrt/errno.h>
5 #include <msvcrt/stdlib.h>
12 strtol(const char *nptr, char **endptr, int base)
18 int neg = 0, any, cutlim;
21 * Skip white space and pick up leading +/- sign if any.
22 * If base is 0, allow 0x for hex and 0 for octal, else
23 * assume decimal; if base is already 16, allow 0x.
35 if ((base == 0 || base == 16) &&
36 c == '0' && (*s == 'x' || *s == 'X'))
43 base = c == '0' ? 8 : 10;
46 * Compute the cutoff value between legal numbers and illegal
47 * numbers. That is the largest legal value, divided by the
48 * base. An input number that is greater than this value, if
49 * followed by a legal input character, is too big. One that
50 * is equal to this value may be valid or not; the limit
51 * between valid and invalid numbers is then based on the last
52 * digit. For instance, if the range for longs is
53 * [-2147483648..2147483647] and the input base is 10,
54 * cutoff will be set to 214748364 and cutlim to either
55 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
56 * a value > 214748364, or equal but the next digit is > 7 (or 8),
57 * the number is too big, and we will return a range error.
59 * Set any if any `digits' consumed; make it negative to indicate
62 cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
63 cutlim = cutoff % (unsigned long)base;
64 cutoff /= (unsigned long)base;
65 for (acc = 0, any = 0;; c = *s++)
70 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
75 if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
86 acc = neg ? LONG_MIN : LONG_MAX;
92 *endptr = any ? (char *)s - 1 : (char *)nptr;