From: berg@physik.tu-muenchen.de (Stephen R. van den Berg)
Newsgroups: alt.hackers
Subject: Who can beat this strtol replacement?
Date: 11 Sep 91 18:15:37 GMT
Organization: RBI - RWTH Aachen
Nntp-Posting-Host: messua

If you happen to lack the strtol() function, this should be an exact
replacement.

Now, anybody who has time to spare should:
	- see if (s)he can find any discrepancies between this implementation
	  and the manual specs.
	- try to optimize this code (so that it is smaller and faster (in
	  that order) when compiled).

-----------------------------------cut here--------------------------------
#define const					    /* for the ANSI impaired */

long strtol(str,ptr,base)const char*str,**const ptr;{long result=0;
 unsigned i;int sign=0;		   /* exact library susbstitute for strtol() */
 if(base>=36||base<0)
   goto fault;
 for(;;str++){					  /* skip leading whitespace */
   switch(*str){
      case '\t':case '\n':case '\v':case '\f':case '\r':case ' ':continue;}
   break;}
 switch(*str){						       /* any signs? */
   case '-':sign=1;
   case '+':str++;}
 if(*str=='0'){						 /* leading zero(s)? */
   while((i= *++str)=='0');					   /* skip'm */
   if(i=='x'||i=='X')					/* leading 0x or 0X? */
      if(!base||base==16){
	 base=16;str++;}			    /* hexadecimal all right */
      else
	 goto fault;
   else if(!base)
      base=8;}						 /* then it is octal */
 else if(!base)
   base=10;						  /* or else decimal */
 for(;;result=result*base+i,str++){			 /* start converting */
   if((i= *str-'0')<10);
   else if(i-'A'+'0'<26)
      i-='A'-10-'0';
   else if(i-'a'+'0'<26)
      i-='a'-10-'0';
   else
      break;						/* not of this world */
   if(i>=base)					 /* not of this world either */
      break;}
fault:
 if(ptr)
   *ptr=str;					       /* how far did we get */
 return sign?-result:result;}
#endif
-----------------------------------cut here--------------------------------
--
Sincerely,                                berg@messua.informatik.rwth-aachen.de
           Stephen R. van den Berg (AKA BuGless).    berg@physik.tu-muenchen.de

"I have a *cunning* plan!"
