home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / magazine / drdobbs / c_spec / sources / stoi.c < prev    next >
Text File  |  1986-02-20  |  2KB  |  95 lines

  1. /* STOI.C    More powerful version of atoi.
  2.  *
  3.  *    Copyright (C) 1985 by Allen  Holub.  All rights reserved. 
  4.  *    This program may be copied for personal, non-profit use only.
  5.  */
  6.  
  7. #define islower(c)    ( 'a' <= (c) && (c) <= 'z' )
  8. #define toupper(c)    ( islower(c) ? (c) - ('a' - 'A') : (c) )
  9.  
  10. int        stoi(instr)
  11. register char    **instr;
  12. {
  13.     /*    Convert string to integer. If string starts with 0x it is
  14.      *    interpreted as a hex number, else if it starts with a 0 it
  15.      *    is octal, else it is decimal. Conversion stops on encountering
  16.      *    the first character which is not a digit in the indicated
  17.      *    radix. *instr is updated to point past the end of the number.
  18.      */
  19.  
  20.     register int    num  = 0 ;
  21.     register char    *str     ;
  22.     int        sign = 1 ;
  23.  
  24.     str = *instr;
  25.  
  26.     while(*str == ' '  ||  *str == '\t'  ||  *str == '\n' )
  27.         str++ ;
  28.  
  29.     if( *str == '-' )
  30.     {
  31.         sign = -1 ;
  32.         str++;
  33.     }
  34.  
  35.     if(*str == '0')
  36.     {
  37.         ++str;
  38.         if (*str == 'x'  ||  *str == 'X')
  39.         {
  40.             str++;
  41.             while(  ('0'<= *str && *str <= '9') ||
  42.                 ('a'<= *str && *str <= 'f') ||
  43.                 ('A'<= *str && *str <= 'F')  )
  44.             {
  45.                 num *= 16;
  46.                 num += ('0'<= *str && *str <= '9') ?
  47.                     *str - '0'            :
  48.                     toupper(*str) - 'A' + 10   ;
  49.                 str++;
  50.             }
  51.         }
  52.         else
  53.         {
  54.             while( '0' <= *str  &&  *str <= '7' )
  55.             {
  56.                 num *= 8;
  57.                 num += *str++ - '0' ;
  58.             }
  59.         }
  60.     }
  61.     else
  62.     {
  63.         while( '0' <= *str  &&  *str <= '9' )
  64.         {
  65.             num *= 10;
  66.             num += *str++ - '0' ;
  67.         }
  68.     }
  69.  
  70.     *instr = str;
  71.     return( num * sign );
  72. }
  73.  
  74. #ifdef TEST
  75.  
  76.  
  77. main()
  78. {
  79.     int    num;
  80.     char    numbuf[80], *p;
  81.  
  82.     printf("Use ^C to exit\n");
  83.  
  84.     while( 1 )
  85.     {
  86.         printf("string ( 0x.. 0.. ... ): ");
  87.         gets( p = numbuf );
  88.         num = stoi( &p )  ;
  89.         printf( "<%s> = %d = 0x%x = %o octal   ", numbuf,num,num,num);
  90.         printf( "string tail = <%s>\n", p );
  91.     }
  92. }
  93.  
  94. #endif
  95.