home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power-Programmierung
/
CD1.mdf
/
magazine
/
drdobbs
/
c_spec
/
execute
/
stoi.c
< prev
next >
Wrap
Text File
|
1986-02-20
|
2KB
|
95 lines
/* STOI.C More powerful version of atoi.
*
* Copyright (C) 1985 by Allen Holub. All rights reserved.
* This program may be copied for personal, non-profit use only.
*/
#define islower(c) ( 'a' <= (c) && (c) <= 'z' )
#define toupper(c) ( islower(c) ? (c) - ('a' - 'A') : (c) )
int stoi(instr)
register char **instr;
{
/* Convert string to integer. If string starts with 0x it is
* interpreted as a hex number, else if it starts with a 0 it
* is octal, else it is decimal. Conversion stops on encountering
* the first character which is not a digit in the indicated
* radix. *instr is updated to point past the end of the number.
*/
register int num = 0 ;
register char *str ;
int sign = 1 ;
str = *instr;
while(*str == ' ' || *str == '\t' || *str == '\n' )
str++ ;
if( *str == '-' )
{
sign = -1 ;
str++;
}
if(*str == '0')
{
++str;
if (*str == 'x' || *str == 'X')
{
str++;
while( ('0'<= *str && *str <= '9') ||
('a'<= *str && *str <= 'f') ||
('A'<= *str && *str <= 'F') )
{
num *= 16;
num += ('0'<= *str && *str <= '9') ?
*str - '0' :
toupper(*str) - 'A' + 10 ;
str++;
}
}
else
{
while( '0' <= *str && *str <= '7' )
{
num *= 8;
num += *str++ - '0' ;
}
}
}
else
{
while( '0' <= *str && *str <= '9' )
{
num *= 10;
num += *str++ - '0' ;
}
}
*instr = str;
return( num * sign );
}
#ifdef TEST
main()
{
int num;
char numbuf[80], *p;
printf("Use ^C to exit\n");
while( 1 )
{
printf("string ( 0x.. 0.. ... ): ");
gets( p = numbuf );
num = stoi( &p ) ;
printf( "<%s> = %d = 0x%x = %o octal ", numbuf,num,num,num);
printf( "string tail = <%s>\n", p );
}
}
#endif