itoa'd you so?

Derek Davis derek.davis at gmail.com
Thu Sep 20 08:53:47 MDT 2007


On 9/19/07, Dave Smith <dave at thesmithfam.org> wrote:
> So now I'm curious. What is sprintf() doing that is so much faster. I
> mean, it has to parse a format string in addition to doing all the itoa
> magic. Anyone care to shed some light? Is my algorithm flawed by design
> (like most of my code)?
>
> Off to read the sprintf() code...
>
> --Dave

Why not.  I'll post my answer just since it came out faster than
sprintf.  Well, when I pass in a buffer, rather than allocating it in
the function.  Don't know about the speed comparison when allocating.
Not that this answers your question...

------------------------------------------------------

/* This space reserved for comments. */
char * itoa(int num)
{
        int tmp = num;
        int digits = 0;
        while(tmp)
        {
                tmp/=10;
                digits++;
        }
        if(num < 0)
                digits++;
        char *res = new char[digits+1];
        res[digits--] = 0;
        if(num < 0)
        {
                res[0] = '-';
                tmp = num * -1;
        }
        else
                tmp = num;
        while(tmp)
        {
                res[digits--] = '0' + tmp%10;
                tmp/=10;
        }
        return res;
}



More information about the PLUG mailing list