1 /* Copyright (C) 1994 DJ Delorie, see COPYING.DJ for details */
8 strtol(const char *nptr, char **endptr, int base)
14 int neg = 0, any, cutlim;
17 * Skip white space and pick up leading +/- sign if any.
18 * If base is 0, allow 0x for hex and 0 for octal, else
19 * assume decimal; if base is already 16, allow 0x.
31 if ((base == 0 || base == 16) &&
32 c == '0' && (*s == 'x' || *s == 'X'))
39 base = c == '0' ? 8 : 10;
42 * Compute the cutoff value between legal numbers and illegal
43 * numbers. That is the largest legal value, divided by the
44 * base. An input number that is greater than this value, if
45 * followed by a legal input character, is too big. One that
46 * is equal to this value may be valid or not; the limit
47 * between valid and invalid numbers is then based on the last
48 * digit. For instance, if the range for longs is
49 * [-2147483648..2147483647] and the input base is 10,
50 * cutoff will be set to 214748364 and cutlim to either
51 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
52 * a value > 214748364, or equal but the next digit is > 7 (or 8),
53 * the number is too big, and we will return a range error.
55 * Set any if any `digits' consumed; make it negative to indicate
58 cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
59 cutlim = cutoff % (unsigned long)base;
60 cutoff /= (unsigned long)base;
61 for (acc = 0, any = 0;; c = *s++)
66 c -= isupper(c) ? 'A' - 10 : 'a' - 10;
71 if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
82 acc = neg ? LONG_MIN : LONG_MAX;
87 *endptr = any ? (char *)s - 1 : (char *)nptr;