xref: /titanic_41/usr/src/lib/libbc/libc/gen/common/strtol.c (revision 6dfee4834394825da35b977ca71cdc965bc7b6a4)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*      Copyright (c) 1984 AT&T */
23 /*        All Rights Reserved   */
24 
25 #pragma ident	"%Z%%M%	%I%	%E% SMI"  /* from S5R2 2.1 */
26 
27 /*LINTLIBRARY*/
28 #include <ctype.h>
29 #define DIGIT(x)	(isdigit(x) ? (x) - '0' : \
30 			islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A')
31 #define MBASE	('z' - 'a' + 1 + 10)
32 
33 long
34 strtol(str, ptr, base)
35 register char *str;
36 char **ptr;
37 register int base;
38 {
39 	register long val;
40 	register int c;
41 	int xx, neg = 0;
42 
43 	if (ptr != (char **)0)
44 		*ptr = str; /* in case no number is formed */
45 	if (base < 0 || base > MBASE)
46 		return (0); /* base is invalid -- should be a fatal error */
47 	if (!isalnum(c = *str)) {
48 		while (isspace(c))
49 			c = *++str;
50 		switch (c) {
51 		case '-':
52 			neg++;
53 		case '+': /* fall-through */
54 			c = *++str;
55 		}
56 	}
57 	if (base == 0)
58 		if (c != '0')
59 			base = 10;
60 		else if (str[1] == 'x' || str[1] == 'X')
61 			base = 16;
62 		else
63 			base = 8;
64 	/*
65 	 * for any base > 10, the digits incrementally following
66 	 *	9 are assumed to be "abc...z" or "ABC...Z"
67 	 */
68 	if (!isalnum(c) || (xx = DIGIT(c)) >= base)
69 		return (0); /* no number formed */
70 	if (base == 16 && c == '0' && isxdigit(str[2]) &&
71 	    (str[1] == 'x' || str[1] == 'X'))
72 		c = *(str += 2); /* skip over leading "0x" or "0X" */
73 	for (val = -DIGIT(c); isalnum(c = *++str) && (xx = DIGIT(c)) < base; )
74 		/* accumulate neg avoids surprises near MAXLONG */
75 		val = base * val - xx;
76 	if (ptr != (char **)0)
77 		*ptr = str;
78 	return (neg ? val : -val);
79 }
80