上篇文章说到linux需要itoa函数,下面我就提供一份跨平台的itoa函数。
//return the length of result string. support only 10 radix for easy use and better performance
int my_itoa(int val, char* buf)
{
const int radix = 10;
char* p;
int a; //every digit
int len;
char* b; //start of the digit char
char temp;
p = buf;
if (val < 0)
{
*p++ = '-';
val = 0 - val;
}
b = p;
do
{
a = val % radix;
val /= radix;
*p++ = a + '0';
} while (val > 0);
len = (int)(p - buf);
*p-- = 0;
//swap
do
{
temp = *p;
*p = *b;
*b = temp;
--p;
++b;
} while (b < p);
return len;
}
这个函数会返回字符串的长度,在某些场合下会很有用。
我测试了一下,这个函数大概比MFC自带的itoa要快20%左右。
(因为不需要在循环体内判断if (a > 9)了,所以更快)。
2010/1/8 改进版:
//return the length of result string. support only 10 radix for easy use and better performance
int my_itoa(int val, char* buf)
{
const unsigned int radix = 10;
char* p;
unsigned int a; //every digit
int len;
char* b; //start of the digit char
char temp;
unsigned int u;
p = buf;
if (val < 0)
{
*p++ = '-';
val = 0 - val;
}
u = (unsigned int)val;
b = p;
do
{
a = u % radix;
u /= radix;
*p++ = a + '0';
} while (u > 0);
len = (int)(p - buf);
*p-- = 0;
//swap
do
{
temp = *p;
*p = *b;
*b = temp;
--p;
++b;
} while (b < p);
return len;
}
改进:将除法运算从有符号整数改为了无符号整数。典型速度从240毫秒左右,提高到了180毫秒左右。作为对比,MFC自带的itoa耗时是320毫秒左右。
(x86机器做无符号整数的除法要更快一些,汇编指令不同)
分享到:
相关推荐
本篇文章是对C++实现函数itoa()进行了详细的分析介绍,需要的朋友参考下
itoa函数及atoi函数的区别,C++,MFC
itoa函数的实现 用C语言写的 很简单的 大家可以参考下
标准函数库itoa和strlen的实现,C语言源码 学习自己实现数值转字符itoa函数和求字符串长度strlen函数
学习自己实现数值转字符itoa函数、字符串转数值atoi函数和求字符串长度strlen函数
这是我自己在使用过程中整理下来的,欢迎大家下载查看,谢谢各位的支持
我们都知道在linux下是没有itoa函数的,而又不能通过sprintf实现int转二进制字符串的方式,因此手动编写此代码段,希望可以对大家有帮助。
C语言中实现itoa函数的实例 一、原型: char *itoa( int value, char *string,int radix); 二、函数说明: value:欲转换的数据。 string:目标字符串的地址。 radix:转换后的进制数,可以是10进制、16进制等。...
本文介绍了,atoi和itoa函数的实现方法,需要的朋友可以参考一下
自己编写的整型转字符串函数,在库函数里没有找到,就自己编了个,实用。
本篇文章是对atoi()与itoa()函数的用法进行了详细的分析介绍,需要的朋友参考下
字符串和整形互相转换函数atoi,itoa函数原型认识两个函数以及用法
本篇文章是对atoi()与itoa()函数的内部实现方法进行了详细的分析介绍,需要的朋友参考下
字符串和整形互相转换函数atoi,itoa函数原型 认识两个函数以及用法
itoa-benchmark, C 整数到字符串转换基准 itoa基准测试Copyright(c) 2014 -2016 ( miloyip@gmail.com )简介这个基准评估从 32 -bit/64位 整数转换为十进制字符串的性能。 函数Prototype包括:void u32
itoa 字符函数 isalnum isalpha iscntrl isdigit islower isascii isgraph isprint ispunct isspace isupper isxdigit toascii tolower toupper 内存管理函数 calloc free malloc realloc