/////////////////////////////////////////////////////////////////////////////
//
jeff_itoa.c
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008, Morning Glory Technologies.
All rights reserved.
//
// This program is the property of Morning Glory
Technologies. It contains
// valuable proprietary trade secret information
and is only for use by duly
// licensed customers. This program may not be
copied or transferred to
// any third party without the written permission
of Morning Glory
// Technologies.
//
///////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
char *itoa(int);
int main(int argc, char **argv)
{
int iInt = 0;
float fFloat = 0.00;
if( argc < 2 ) {
fprintf(stdout,"\nUsage: %s
<String (0-65535.00)>\n", argv[0]);
exit(-1);
}
fFloat = stringToFloat(argv[1]);
iInt = atoi(argv[1]);
fprintf(stdout,"\n%d %f\n",
iInt, fFloat);
exit(0);
}
///////////////////////////////////////////////////////////////////////////
float stringToFloat(char *sFloat)
{
float fString = 0.00;
float fMagnitute = 1.00;
char *pFloat;
int Decimal = 0;
int Valid = 0;
if( sFloat == (char *) '\0') {
goto INVALID;
}
//find the magntitue of a whole number
pFloat
= sFloat;
while( *sFloat ) {
if (*sFloat == '.') {
goto BREAK;
}
fMagnitute *= 10;
sFloat++;
}
BREAK:
fMagnitute
/= 10;
sFloat
= pFloat;
while(
*sFloat) {
//switch arithmetic operations
if( *sFloat == '.') {
Decimal =
1;
fMagnitute
= 10.00;
}
if( *sFloat >= '0') {
if( *sFloat <= '9') {
Valid = 1;
}
}
if( Valid ) {
if( !Decimal) {
fString += (*sFloat - '0') * fMagnitute;
fMagnitute /= 10.00;
}
if( Decimal) {
fString += (*sFloat - '0') / fMagnitute;
fMagnitute *= 10.00;
}
}
if( !Valid) {
if( *sFloat != '.') {
fString /= 10;
goto INVALID;
}
}
Valid = 0;
sFloat++;
}
INVALID:
return(fString);
}
///////////////////////////////////////////////////////////////////////////
char *itoa(iInput)
{
char *pReverse;
if( !(pReverse = (char *)calloc(5,sizeof(char)) )) {
fprintf(stderr,"\nCan`t allocate 5 bytes\n");
return( (char *)'0' );
}
//METHOD 1: just use sprintf...
//sprintf(pReverse,"%d",iInput);
//return(pReverse);
//METHOD 2: re-write sprintf...
int iSave = iInput;
int iSave2;
char *pSavePtr;
pSavePtr =
pReverse;
// use subtraction to get units digit.
while( iSave ) {
if( iSave == iInput) {
iSave2 = (iInput / 10) * 10;
fprintf(stdout,"iSave: %d
diff: %d\n", iInput,
iInput - iSave2);
*pReverse = (char
)(iInput - iSave2) + '0';
}
if( iSave != iInput ) {
iSave2 = (iSave / 10) * 10;
fprintf(stdout,"iSave: %d
diff: %d\n", iSave,
iSave - iSave2);
*pReverse = (char
)(iSave - iSave2) + '0';
}
pReverse++;
iSave /= 10;
}
// reverse the string order
char *pRet;
if( !(pRet = (char *)calloc(5,sizeof(char)) )) {
fprintf(stderr,"\nCan`t allocate 5 bytes\n");
return( (char *)'0' );
}
while( pReverse-- >=
pSavePtr ) {
strncat(pRet,pReverse,1);
}
free
(*pReverse);
return( pRet );
}