高效实现整型数字转字符串int2str的方法
时间:2021-05-21 08:26:52|栏目:C代码|点击: 次
将数字转换成字符串有很多方法,现在给出一种高效的实现方法。开阔眼界。
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;
}
以上是没有考虑那么一点点空间的问题;如果考虑那点空间问题,可以这样做。
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;
}
同样,带符号的整数一样的做法。
栏 目:C代码
本文地址:http://www.codeinn.net/misctech/125901.html






