Subversion Repositories Kolibri OS

Rev

Rev 9081 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int getdigit(char ch, int base)
  6. {
  7.     if (isdigit(ch))
  8.         ch -= '0';
  9.     else if (isalpha(ch) && ch <= 'Z')
  10.         ch = 10 + ch - 'A';
  11.     else if (isalpha(ch))
  12.         ch = 10 + ch - 'a';
  13.     else
  14.         return -1;
  15.  
  16.     if (ch / base != 0)
  17.         return -1;
  18.  
  19.     return ch;
  20. }
  21.  
  22. long int strtol(const char* str, char** endptr, int base)
  23. {
  24.     long int res = 0;
  25.     int sign = 1;
  26.  
  27.     if (base > 36) {
  28.         errno = EINVAL;
  29.         goto bye;
  30.     }
  31.  
  32.     while (isspace(*str))
  33.         str++;
  34.  
  35.     if (*str == '-') {
  36.         sign = -1;
  37.         str++;
  38.     } else if (*str == '+')
  39.         str++;
  40.  
  41.     if (base == 0 || base == 16) {
  42.         if (*str == '0' && (str[1] == 'x' || str[1] == 'X')) {
  43.             base = 16;
  44.             str += 2;
  45.         }
  46.     }
  47.  
  48.     if (base == 0 && *str == '0')
  49.         base = 8;
  50.  
  51.     if (base == 0)
  52.         base = 10;
  53.  
  54.     int digit;
  55.     while ((digit = getdigit(*str, base)) >= 0) {
  56.         res = base * res + digit;
  57.         str++;
  58.         if (res < 0) {
  59.             errno = ERANGE;
  60.             if (sign > 0)
  61.                 res = LONG_MAX;
  62.             else
  63.                 res = LONG_MIN;
  64.         }
  65.     }
  66.  
  67. bye:
  68.     if (endptr)
  69.         *endptr = (char*)str;
  70.  
  71.     return res * sign;
  72. }
  73.