int get_digits (int num)
{
if(num < 10)
return 1;
if(num < 100)
return 2;
if(num < 1000)
return 3;
if(num < 10000)
return 4;
if(num < 100000)
return 5;
if(num < 1000000)
return 6;
if(num < 10000000)
return 7;
if(num < 100000000)
return 8;
if(num < 1000000000)
return 9;
return 10; /* num > 1000000000 */
}
char *itoa (int n)
{
static char temp[10]; // MN that can be replaced by some def?
int nDigits = 0;
int i = 0;
if(n == 0)
{
temp[0] = '0';
temp[1] = '\0';
return temp; // or just return "0"; ?
}
nDigits = get_digits(n); // fast function to count digits..
temp[nDigits] = '\0'; // ..needed just here
for(i = n; i >= 1; i /= 10) // whole method stinks
{
temp[--nDigits] = ((i % 10) + '0'); // modulo is quite slow
}
return temp;
}
This is my implementation of the infamous function itoa()
, which isn't available everywhere and more importantly not available in my environment. Generally, the implementation of this function is ought to be different anyway. Performance and memory optimization is important.
This function converts an integer to a string. The function owns the reference to the returned string, which is statically allocated and the caller is responsible to make a copy of the returned string if he plans on changing it or preserving it across subsequent calls.
n == 0
(since you will get the correct output with the rest of the code).get_digits
(which should be completely eliminated) could possibly be improved a bit with some nested conditionals (if (num < 100) return num < 10 ? 1 : 2;
), although smaller numbers will be more common that larger ones. \$\endgroup\$ – 1201ProgramAlarm Jun 12 '20 at 18:04i >= 1
, therefore the special case forn == 0
is indeed needed. \$\endgroup\$ – Roland Illig Jun 13 '20 at 5:02i = n; do { ... } while ((i /= 10) >= 1);
to avoid the overhead of a probably rarely needed special case. \$\endgroup\$ – 1201ProgramAlarm Jun 13 '20 at 17:56