xref: /original-bsd/lib/libc/stdlib/strtol.c (revision 6570ed16)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #if defined(LIBC_SCCS) && !defined(lint)
9 static char sccsid[] = "@(#)strtol.c	5.3 (Berkeley) 05/17/90";
10 #endif /* LIBC_SCCS and not lint */
11 
12 #include <limits.h>
13 #include <ctype.h>
14 #include <errno.h>
15 #include <stdlib.h>
16 
17 
18 /*
19  * Convert a string to a long integer.
20  *
21  * Ignores `locale' stuff.  Assumes that the upper and lower case
22  * alphabets and digits are each contiguous.
23  */
24 long
25 strtol(nptr, endptr, base)
26 	char *nptr, **endptr;
27 	register int base;
28 {
29 	register char *s = nptr;
30 	register unsigned long acc;
31 	register int c;
32 	register unsigned long cutoff;
33 	register int neg = 0, any, cutlim;
34 
35 	/*
36 	 * Skip white space and pick up leading +/- sign if any.
37 	 * If base is 0, allow 0x for hex and 0 for octal, else
38 	 * assume decimal; if base is already 16, allow 0x.
39 	 */
40 	do {
41 		c = *s++;
42 	} while (isspace(c));
43 	if (c == '-') {
44 		neg = 1;
45 		c = *s++;
46 	} else if (c == '+')
47 		c = *s++;
48 	if ((base == 0 || base == 16) &&
49 	    c == '0' && (*s == 'x' || *s == 'X')) {
50 		c = s[1];
51 		s += 2;
52 		base = 16;
53 	}
54 	if (base == 0)
55 		base = c == '0' ? 8 : 10;
56 
57 	/*
58 	 * Compute the cutoff value between legal numbers and illegal
59 	 * numbers.  That is the largest legal value, divided by the
60 	 * base.  An input number that is greater than this value, if
61 	 * followed by a legal input character, is too big.  One that
62 	 * is equal to this value may be valid or not; the limit
63 	 * between valid and invalid numbers is then based on the last
64 	 * digit.  For instance, if the range for longs is
65 	 * [-2147483648..2147483647] and the input base is 10,
66 	 * cutoff will be set to 214748364 and cutlim to either
67 	 * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
68 	 * a value > 214748364, or equal but the next digit is > 7 (or 8),
69 	 * the number is too big, and we will return a range error.
70 	 *
71 	 * Set any if any `digits' consumed; make it negative to indicate
72 	 * overflow.
73 	 */
74 	cutoff = neg ? -(unsigned long)LONG_MIN : LONG_MAX;
75 	cutlim = cutoff % (unsigned long)base;
76 	cutoff /= (unsigned long)base;
77 	for (acc = 0, any = 0;; c = *s++) {
78 		if (isdigit(c))
79 			c -= '0';
80 		else if (isalpha(c))
81 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
82 		else
83 			break;
84 		if (c >= base)
85 			break;
86 		if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
87 			any = -1;
88 		else {
89 			any = 1;
90 			acc *= base;
91 			acc += c;
92 		}
93 	}
94 	if (any < 0) {
95 		acc = neg ? LONG_MIN : LONG_MAX;
96 		errno = ERANGE;
97 	} else if (neg)
98 		acc = -acc;
99 	if (endptr != 0)
100 		*endptr = any ? s - 1 : nptr;
101 	return (acc);
102 }
103