实现itoa

jianjunlena 2010-03-07 09:44:38
linux平台下有atoi,而没有itoa,因此想实现一个跨平台的itoa,大家给个思路?不想用sprintf,它的效率太低。
...全文
181 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Crob 2010-03-07
  • 打赏
  • 举报
回复
我认为这种函数,最简单最白痴的算法就是最快的算法。
将一个int逐位取模然后再搞一个0到9的大大的switch case语句输出。

magic7004 2010-03-07
  • 打赏
  • 举报
回复
晕又错了,csdn应该允许编辑自己的帖子才对。
看这个
char* itoa(int value, char *string, int radix) 
{
if(string == NULL) return NULL;
if(radix <2 || radix > 36)
{
string[0] = 0;
return string;
}
static int i = 0;
if(value < 0)
{
string[i]='-';
i++;
value = -1 * value;
}
if(value / radix > 0) itoa(value/radix,string,radix);
if(value % radix < 10) string[i]=value % radix + '0';
else string[i] = value % radix - 10 + 'A';
string[i+1]=0;
i++;
return string;
}
magic7004 2010-03-07
  • 打赏
  • 举报
回复
上面的代码写错了,应该是这个
char* itoa(int value, char *string, int radix)
{
if(string == NULL) return NULL;
if(radix <2 || radix > 36)
{
string[0] = 0;
return string;
}
static int i = 0;
if(value < 0)
{
string[i]='-';
i++;
value = -1 * value;
}
if(value / radix > 0) itoa(value/radix,string,radix);
if(value % radix < 10) string[i]=value % radix + '0';
else string[i] = value % radix - 10 + 'A';
string[i+1]=0;
i++;
return string;
}
magic7004 2010-03-07
  • 打赏
  • 举报
回复
其实用sprintf挺好的,这点效率可以忽略了。现在的cpu和内存都足够的。
而且自己写一个itoa效率也不一定会比sprintf高吧。

我写的这个貌似效率就挺低的
char* asd (int value, char *string, int radix)
{
static int i = 0;
if(value < 0)
{
string[i]='-';
i++;
value = -1 * value;
}
if(value / radix > 0)
itoa(value/radix,string,radix);
if(value % radix < 10)
string[i]=value % radix + '0';
else
string[i] = value % radix - 10 + 'A';
string[i+1]=0;
i++;
return string;
}
yyg990441 2010-03-07
  • 打赏
  • 举报
回复

char *myitoa( int value, char *str, int radix =10 )
{
static char szMap[] = {
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b',
'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
}; // 字符映射表
int nCount = -1, nIndex;
char *pStr = str, nTemp;
if ( radix >= 2 && radix <= 36 )
{ // 限制radix必须在2到36之间
if ( value < 0 && radix == 10 )
{ // 如果是负数就在首位添加负号,并将字符串前移
*pStr++ = '-';
value = -value; //转为正数,
}
unsigned int nValue = *(unsigned*)&value;
do { // 循环转换每一个数字,直到结束
pStr[ ++nCount ] = szMap[ nValue % radix ];
nValue /= radix;
} while( nValue > 0 ); // 转换结束后字符串是翻的
nIndex = ( nCount + 1 ) / 2; // 计算出一半的长度
while( nIndex-- > 0 ) { // 将字符串的字符序翻转
nTemp = pStr[ nIndex ];
pStr[ nIndex ] = pStr[ nCount - nIndex ];
pStr[ nCount - nIndex ] = nTemp;
}
}
pStr[ nCount + 1 ] = '\0'; // 置结束符
return str;
}
jianjunlena 2010-03-07
  • 打赏
  • 举报
回复
自己先顶个啊!!!!!!!!!!!!!!!!!

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧