Efficient implementation of integer numeric string int2str method

  • 2020-05-17 05:58:41
  • OfStack

There are many ways to convert a number to a string, but here is an efficient way to do it. Broaden your horizons.


char* int2str(unsigned int values)
{
  const char digits[11] = "0123456789";
  char* crtn = new char[32];
  crtn += 31;
  *crtn = '\0';
  do 
  {
    *--crtn = digits[values%10];
  } while (values /= 10);

  return crtn;
}

The above is not considered so 1 little space problem; And if you think about that little bit of space, you can do that.


char* int2str(unsigned int values)
{
  int len = 0;
 const char digits[11] = "0123456789";
 unsigned int tvalue = values;
 while(tvalue >= 100)
 {
 tvalue /= 100;
 len += 2;
 }
 if (tvalue > 10)
 len += 2;
 else if(tvalue > 0)
 len++;

 char* crtn = new char[len+1];
 crtn += len;
 *crtn = '\0';
 do 
 {
 *--crtn = digits[values%10];
 } while (values /= 10);

 return crtn; 
}

Similarly, a signed integer like 1 is used.


Related articles: