ack/lang/cem/libcc.ansi/stdlib/strtol.c

99 lines
2.2 KiB
C
Raw Normal View History

1989-05-16 13:13:53 +00:00
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*/
/* $Header$ */
#include <ctype.h>
1989-12-18 15:14:14 +00:00
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
static unsigned long
string2long(register const char *nptr, char **endptr,
int base, int is_signed);
1989-05-16 13:13:53 +00:00
long int
1989-12-18 15:14:14 +00:00
strtol(register const char *nptr, char **endptr, int base)
{
return (signed long)string2long(nptr, endptr, base, 1);
}
unsigned long int
strtoul(register const char *nptr, char **endptr, int base)
{
return (unsigned long)string2long(nptr, endptr, base, 0);
}
static unsigned long
string2long(register const char *nptr, char ** const endptr,
int base, int is_signed)
1989-05-16 13:13:53 +00:00
{
1989-12-18 15:14:14 +00:00
register int v;
register unsigned long val = 0;
1989-05-16 13:13:53 +00:00
register int c;
1989-12-18 15:14:14 +00:00
int ovfl = 0, sign = 1;
const char *startnptr = nptr, *nrstart;
if (endptr) *endptr = (char *)nptr;
while (isspace(*nptr)) nptr++;
c = *nptr;
if (c == '-' || c == '+') {
if (c == '-') sign = -1;
nptr++;
1989-05-16 13:13:53 +00:00
}
1989-12-18 15:14:14 +00:00
nrstart = nptr; /* start of the number */
/* When base is 0, the syntax determines the actual base */
if (base == 0)
if (*nptr == '0')
if (*++nptr == 'x' || *nptr == 'X') {
base = 16;
nptr++;
}
else base = 8;
else base = 10;
else if (base==16 && *nptr=='0' && (*++nptr =='x' || *nptr =='X'))
nptr++;
1989-05-16 13:13:53 +00:00
1989-12-18 15:14:14 +00:00
while (isdigit(c = *nptr) || isalpha(c)) {
if (!ovfl) {
if (isalpha(c))
v = 10 + (isupper(c) ? c - 'A' : c - 'a');
else
v = c - '0';
if (v >= base) break;
if (val > (ULONG_MAX - v) / base) ovfl++;
val = (val * base) + v;
1989-05-16 13:13:53 +00:00
}
1989-12-18 15:14:14 +00:00
nptr++;
}
if (endptr) {
if (nrstart == nptr) *endptr = (char *)startnptr;
else *endptr = (char *)nptr;
1989-05-16 13:13:53 +00:00
}
1989-12-18 15:14:14 +00:00
/* We can't represent a negative unsigned long, nor a long that
* is smaller than LONG_MIN or larger than LONG_MAX.
*/
if (!ovfl) {
if (!is_signed)
if (sign < 0 && val != 0)
ovfl++;
else if (((sign < 0 && val > -LONG_MIN)
|| (sign > 0 && val > LONG_MAX)))
ovfl++;
}
1989-05-16 13:13:53 +00:00
1989-12-18 15:14:14 +00:00
if (ovfl) {
errno = ERANGE;
if (is_signed)
if (sign < 0) return LONG_MIN;
else return LONG_MAX;
else return ULONG_MAX;
}
if (is_signed) return (unsigned long) sign * val;
else return val;
1989-05-16 13:13:53 +00:00
}