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