integer to string function (itoa())
Dan KoGai
dankg at monsoon.Berkeley.EDU
Sat Jun 30 17:12:29 AEST 1990
In article <153 at travis.csd.harris.com> brad at SSD.CSD.HARRIS.COM (Brad Appleton) writes:
>In article <22888 at boulder.Colorado.EDU> baileyc at tramp.Colorado.EDU (BAILEY CHRISTOPHER R) writes:
>
>>Help, I need an itoa() function for use with my Sun compiler.
>
>Perhaps I missed something but ... Is there some reason why:
>
> int i = 10; char a[3];
> sprintf( a, "%d", i );
>
>is unnacceptable for your purposes?
Maybe. But I was wondering why there's no itoa() in most C libraries:
atoi() exists and often used in scanf(). Why do we let [sf]printf() do
all conversion instead of calling itoa...
itoa() would be not that hard to program. Let me make it up:
/*
* itoa.c
* converts integer to ascii string
*/
char *itoa(int i)
/* or
* char
* itoa(i)
* int i;
*/
{
static char buf[16]; /* twelve will suffice including sign but hell */
char *bufptr = &buf[15]; /* bufptr pts at the end of buf */
char sign = 0;/* true if negative */
*bufptr-- = 0;/* terminate string for sure */
if (i < 0) {
sign = 1; /* set negative */
i = -i; /* i must be positve for do-while loop */
}
do{ /* while fails if i = 0 */
*bufptr-- = i % 10 + '0'; /* sets digit from low to high */
i /= 10;/* shift one digit */
}while(i != 0);
if (sign) {
*bufptr = '-'; /* if negative put '-' */
return bufptr;
}
else return ++bufptr; /* rewind overrun bufptr */
}
/* main() for test */
main(int argc, char **argv){
int i = atoi(argv[1]);
printf("via printf:%d via itoa:%s\n", i, itoa(i));
}
This should work unless your character table is so wierd that it
doesn't have [0-9] consecutively
More information about the Comp.lang.c
mailing list