Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uunet!samsung!usc!ucselx!bionet!agate!monsoon.Berkeley.EDU!dankg From: dankg@monsoon.Berkeley.EDU (Dan KoGai) Newsgroups: comp.lang.c Subject: Re: integer to string function (itoa()) Message-ID: <1990Jun30.071229.23965@agate.berkeley.edu> Date: 30 Jun 90 07:12:29 GMT References: <22888@boulder.Colorado.EDU> <153@travis.csd.harris.com> Sender: usenet@agate.berkeley.edu (USENET Administrator;;;;ZU44) Reply-To: dankg@monsoon.Berkeley.EDU (Dan KoGai) Distribution: usa Organization: ucb Lines: 57 In article <153@travis.csd.harris.com> brad@SSD.CSD.HARRIS.COM (Brad Appleton) writes: >In article <22888@boulder.Colorado.EDU> baileyc@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