123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- #include <ctype.h>
- #include <errno.h>
- #include <inttypes.h>
- intmax_t
- strtoimax(const char *nptr, char **endptr, int base)
- {
- const char *s;
- intmax_t acc, cutoff;
- int c;
- int neg, any, cutlim;
-
- s = nptr;
- do {
- c = (unsigned char) *s++;
- } while (isspace(c));
- if (c == '-') {
- neg = 1;
- c = *s++;
- } else {
- neg = 0;
- if (c == '+')
- c = *s++;
- }
- if ((base == 0 || base == 16) &&
- c == '0' && (*s == 'x' || *s == 'X')) {
- c = s[1];
- s += 2;
- base = 16;
- }
- if (base == 0)
- base = c == '0' ? 8 : 10;
-
- cutoff = neg ? INTMAX_MIN : INTMAX_MAX;
- cutlim = cutoff % base;
- cutoff /= base;
- if (neg) {
- if (cutlim > 0) {
- cutlim -= base;
- cutoff += 1;
- }
- cutlim = -cutlim;
- }
- for (acc = 0, any = 0;; c = (unsigned char) *s++) {
- if (isdigit(c))
- c -= '0';
- else if (isalpha(c))
- c -= isupper(c) ? 'A' - 10 : 'a' - 10;
- else
- break;
- if (c >= base)
- break;
- if (any < 0)
- continue;
- if (neg) {
- if (acc < cutoff || (acc == cutoff && c > cutlim)) {
- any = -1;
- acc = INTMAX_MIN;
- errno = ERANGE;
- } else {
- any = 1;
- acc *= base;
- acc -= c;
- }
- } else {
- if (acc > cutoff || (acc == cutoff && c > cutlim)) {
- any = -1;
- acc = INTMAX_MAX;
- errno = ERANGE;
- } else {
- any = 1;
- acc *= base;
- acc += c;
- }
- }
- }
- if (endptr != 0)
- *endptr = (char *) (any ? s - 1 : nptr);
- return (acc);
- }
|