/* Conversion routine from int to formatted string. Same params as classic ITOA. This version is probably much faster than the one supplied with your compiler. Version 0.2 - added _2dc() and made itoa a special case of _2dc(). Cameron W. Cotrill 9/9/89 */ #include /* find which compiler */ #ifndef BDSC int pwr10[] = {1,10,100,1000,10000}; #endif char *itoa(s,value) int value; char *s; { return(_2dc(s,value,0,TRUE)); } /* General purpose int to decimal conversion routine. Allows signed, unsigned, fixed or variable number of digits. */ _2dc(s,value,digits,sign) char *s; int value; #ifndef BDSC unsigned int digits,sign; #else unsigned digits,sign; #endif { char *t; #ifndef BDSC unsigned int lead0, i, j; #else unsigned lead0, i, j; int pwr10[5]; pwr10[0] = 1; pwr10[1] = 10; pwr10[2] = 100; pwr10[3] = 1000; pwr10[4] = 10000; #endif /* Set first char in string to sign */ t = s; /* Save pointer to start of string for return */ if(!digits) { lead0 = TRUE; /* Set leading 0 flag if digits == 0 */ digits = 5; /* Allow up to 5 digits */ } else lead0 = FALSE; if(value < 0 && sign) { *s++ = '-'; value = -value; } /* Convert value to ascii */ for(i=digits;i--;){ j = '0'; while(value >= pwr10[i]) { ++j; value -= pwr10[i]; } if(!(j == '0' && i)) lead0 = 0; if(!(lead0 && j == '0')) #ifndef BDSC *s++ = (char) j; #else *s++ = j; #endif } *s = '\0'; return(t); } /* Convert ascii numeric representation to int. Leading spaces are ignored. '+' or '-' may preceed number. Numeric conversion stops at the first non-numeric ascii character. */ int atoi(string) char *string; { char c; int i,j; j = 0; c = 0; while(isspace(*string)) ++string; /* skip spaces */ if(*string == '-') /* deal with sign char if present */ c=*string++; if(*string == '+') string++; while(isdigit(*string)) { j<<=1; /* times 2 */ i = j; /* remember this */ j<<=2; /* times 8 now */ j += i; /* would you believe *10? */ j+= *string - '0'; ++string; } return(c?-j:j); }