itoa

Daniel Berlin dberlin@redhat.com
Tue Apr 3 22:15:00 GMT 2001


Francois Gouget <fgouget@free.fr> writes:

> On Tue, 3 Apr 2001 Timothy_Ko@nag.national.com.au wrote:
> 
> > 
> > 
> > Hi,
> > 
> > I have #include stdlib.h
> > 
> > But I still have
> > 
> > implicit declaration of function `int _itoa(...)'
> > 
> > Can anyone help me?
> 
>    AFAIK, this is a microsoft specific function. You can probably
> replace it with a sprintf into a small buffer.

Corrrect. The other option, is, of course, to rewrite itoa from
scratch.
It's not that difficult, I had to do it on a whiteboard at an
interview at Microsoft years ago, without using *printf.

Let's see (I had based what i wrote on the whiteboard off a public domain implementation of ltoa
i once saw, though it's pretty straightforward anyway):

#define BUFSIZE (sizeof(int) * 8 + 1)
char *itoa(int num, char *buf, int base)
{
        int i=2, uarg;
        char *tail, *head = buf, tempbuf[BUFSIZE];

        if (base > 36 || base < 2)
                base = 10;

        tail = &tempbuf[BUFSIZE - 1];
        *tail-- = '\0';
        
        if (base == 10 && num < 0)
        {
                *head++ = '-';
                uarg = -num;
        }
        else
                uarg = num;
       
        if (uarg)
        {
                for (i = 1; uarg; ++i)
                {
                        div_t r;
                        r = div (uarg, base);
                        *tail-- = (char)(r.rem + ((r.rem > 9) ? 
                                        ('A' - 10) : '0'));
                        uarg = r.quot;
                }
        }
        else *tail-- = '0';

        memcpy (head, ++tail, i);
        return buf;
}        


Before anyone points out how horrific this is, I was ~14 at the
time, and the whiteboards aren't all that large.

HTH,
Dan

-- 
I made wine out of raisins so I wouldn't have to wait for it to age.



More information about the Gcc mailing list