Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | Download | RSS feed

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