Okay, here's one that is MUCH faster which I did after reading Weston's (better) code. It's still not quite as fast as the sprintf() version, but much closer (about 25% slower instead of twice as slow).

int pow10i( unsigned int p )
{
   int ret = 1;
   while(p--)
       ret *= 10;
   return ret;
}

void itoa( int value, char *buf )
{
   if( value == 0 )
   {
       buf[0] = '0';
       buf[1] = '\0';
   }
   else
   {
       int i = value;

       if( value < 0 )
       {
           buf[0] = '-';
           i = -i;
       }

       int len = (int)log10( i ) + 1;

       for( int pos=len-1; pos>=0; pos-- )
       {
           int digit = i % 10;
           int index = value < 0 ? pos+1 : pos;
           buf[index] = '0' + digit;
           i /= 10;
       }

       int index = value < 0 ? len+1 : len;
       buf[index] = '\0';
   }
}


/*
PLUG: http://plug.org, #utah on irc.freenode.net
Unsubscribe: http://plug.org/mailman/options/plug
Don't fear the penguin.
*/

Reply via email to