xref: /original-bsd/lib/libc/stdlib/strtoul.c (revision 9f9ff93c)
1 /*
2  * Copyright (c) 1990 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[] = "@(#)strtoul.c	5.2 (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  * Convert a string to an unsigned long integer.
19  *
20  * Ignores `locale' stuff.  Assumes that the upper and lower case
21  * alphabets and digits are each contiguous.
22  */
23 unsigned long
24 strtoul(nptr, endptr, base)
25 	char *nptr, **endptr;
26 	register int base;
27 {
28 	register char *s = nptr;
29 	register unsigned long acc;
30 	register int c;
31 	register unsigned long cutoff;
32 	register int neg = 0, any, cutlim;
33 
34 	/*
35 	 * See strtol for comments as to the logic used.
36 	 */
37 	do {
38 		c = *s++;
39 	} while (isspace(c));
40 	if (c == '-') {
41 		neg = 1;
42 		c = *s++;
43 	} else if (c == '+')
44 		c = *s++;
45 	if ((base == 0 || base == 16) &&
46 	    c == '0' && (*s == 'x' || *s == 'X')) {
47 		c = s[1];
48 		s += 2;
49 		base = 16;
50 	}
51 	if (base == 0)
52 		base = c == '0' ? 8 : 10;
53 	cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
54 	cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
55 	for (acc = 0, any = 0;; c = *s++) {
56 		if (isdigit(c))
57 			c -= '0';
58 		else if (isalpha(c))
59 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
60 		else
61 			break;
62 		if (c >= base)
63 			break;
64 		if (any < 0 || acc > cutoff || acc == cutoff && c > cutlim)
65 			any = -1;
66 		else {
67 			any = 1;
68 			acc *= base;
69 			acc += c;
70 		}
71 	}
72 	if (any < 0) {
73 		acc = ULONG_MAX;
74 		errno = ERANGE;
75 	} else if (neg)
76 		acc = -acc;
77 	if (endptr != 0)
78 		*endptr = any ? s - 1 : nptr;
79 	return (acc);
80 }
81