home *** CD-ROM | disk | FTP | other *** search
/ Simtel MSDOS 1992 December / simtel1292_SIMTEL_1292_Walnut_Creek.iso / msdos / ddjmag / ddj8910.arc / SMITH2.ARC / STOI.C < prev    next >
Text File  |  1989-03-21  |  2KB  |  70 lines

  1. /*  STOI.C   More powerful version of atoi.
  2.  *   from DDJ May 1985.  Copyright Allen Holub.
  3.  */
  4.  
  5. #define islower(c)     ( 'a' <= (c) && (c) <= 'z' )
  6. #define toupper(c)     ( islower(c) ? (c) - 0x20 : (c) )
  7.  
  8. /* ---- stoi:  Converts string to integer.  If string starts with 0x, it is
  9.  *        interpreted as a hex number, else if it starts with a 0, it is
  10.  *        octal, else it is decimal.  Conversion stops on encountering the
  11.  *        first character which is not a digit in the indicated radix.
  12.  *        *instr is updated to point past the end of the number.
  13.  */
  14. int    stoi(instr)
  15.   register char **instr;
  16. {
  17.   register int  num = 0;
  18.   register char *str;
  19.   int           sign = 1;
  20.  
  21.   str = *instr;
  22.  
  23.   while ( *str == ' ' || *str == '\t' || *str == '\n')
  24.     str++;
  25.  
  26.   if (*str == '-' )
  27.   {
  28.     sign = -1;
  29.     str++;
  30.   }
  31.  
  32.   if (*str == '0')
  33.   {
  34.     ++str;
  35.     if (*str == 'x' || *str == 'X')
  36.     {
  37.       str++;
  38.       while ( ( '0' <= *str && *str <= '9') ||
  39.               ( 'a' <= *str && *str <= 'f') ||
  40.               ( 'A' <= *str && *str <= 'F')   )
  41.       {
  42.         num *= 16;
  43.         num += ('0' <= *str && *str <= '9') ? *str - '0'
  44.                                             : toupper(*str) - 'A' + 10 ;
  45.         str++;
  46.       }
  47.     }
  48.     else      /* handle octal */
  49.     {
  50.       while ( '0' <= *str && *str <= '7')
  51.       {
  52.         num *= 8;
  53.         num += *str++ - '0';
  54.       }
  55.     }
  56.   }
  57.   else  /* handle decimal */
  58.   {
  59.     while ( '0' <= *str && *str <= '9')
  60.     {
  61.       num *= 10;
  62.       num += *str++ - '0';
  63.     }
  64.   }
  65.   *instr = str;
  66.   return (num * sign);
  67. }
  68.  
  69.  
  70.