* Copyright (c) 1990 The Regents of the University of California.
* %sccs.include.redist.c%
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid
[] = "@(#)strtol.c 5.4 (Berkeley) %G%";
#endif /* LIBC_SCCS and not lint */
* Convert a string to a long integer.
* Ignores `locale' stuff. Assumes that the upper and lower case
* alphabets and digits are each contiguous.
strtol(nptr
, endptr
, base
)
register const char *s
= nptr
;
register unsigned long acc
;
register unsigned long cutoff
;
register int neg
= 0, any
, cutlim
;
* Skip white space and pick up leading +/- sign if any.
* If base is 0, allow 0x for hex and 0 for octal, else
* assume decimal; if base is already 16, allow 0x.
if ((base
== 0 || base
== 16) &&
c
== '0' && (*s
== 'x' || *s
== 'X')) {
base
= c
== '0' ? 8 : 10;
* Compute the cutoff value between legal numbers and illegal
* numbers. That is the largest legal value, divided by the
* base. An input number that is greater than this value, if
* followed by a legal input character, is too big. One that
* is equal to this value may be valid or not; the limit
* between valid and invalid numbers is then based on the last
* digit. For instance, if the range for longs is
* [-2147483648..2147483647] and the input base is 10,
* cutoff will be set to 214748364 and cutlim to either
* 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated
* a value > 214748364, or equal but the next digit is > 7 (or 8),
* the number is too big, and we will return a range error.
* Set any if any `digits' consumed; make it negative to indicate
cutoff
= neg
? -(unsigned long)LONG_MIN
: LONG_MAX
;
cutlim
= cutoff
% (unsigned long)base
;
cutoff
/= (unsigned long)base
;
for (acc
= 0, any
= 0;; c
= *s
++) {
c
-= isupper(c
) ? 'A' - 10 : 'a' - 10;
if (any
< 0 || acc
> cutoff
|| acc
== cutoff
&& c
> cutlim
)
acc
= neg
? LONG_MIN
: LONG_MAX
;
*endptr
= any
? s
- 1 : (char *)nptr
;