GCC下itoa函数的演变:itoa with GCC

2024-08-28 04:08
文章标签 函数 演变 gcc itoa

本文主要是介绍GCC下itoa函数的演变:itoa with GCC,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文:http://www.strudel.org.uk/itoa/

这篇文章中有对部分函数的具体分析:对itoa函数的分析。

简介

我怎么在GCC下使用itoa()?

          啊,C/C++!itoa()不是ANSI C标准而且它不能在linux下的GCC中工作(至少我使用的版本是这样的)。这是很让人沮丧的,特别是当你想让代码跨平台可用时(Windows/Linux/Solaris或其他任何机器)。

        很多人说可以使用sprintf来写字符串但是sprintf不满足itoa()的一个特征:itoa函数允许将int转换为除十进制以外其他进制的形式。该文章包含一系列itoa函数实现的演化版本。较老的版本在文章后边。请确认你用的是最新版本。

贡献

       在我们继续之前,我要感谢以下为解决方案作出贡献的人。这个函数是由以下人员贡献的:Stuart Lowe (本文作者),Robert Jan Schaper,Ray-Yuan Sheu, Rodrigo de Salvo Braz,Wes Garland,John Maloney,Brian Hunt,Fernando Corradi and Lukás Chmela。


演变过程

以下是早期的一个版本,由Robert Jan Schaper表述于Google groups:

char* version 0.1

char* itoa(int val, int base){static char buf[32] = {0};int i = 30;for(; val && i ; --i, val /= base)buf[i] = "0123456789abcdef"[val % base];return &buf[i+1];
}
我所使用的版本和这个版本看起来不太一样,它更像是这样的形式: itoa(int value, char* buffer, int radix)。在最后,我给出了我自己使用std::string代替字符串的版本。

std::string version 0.1

void my_itoa(int value, std::string& buf, int base){int i = 30;buf = "";for(; value && i ; --i, value /= base) buf = "0123456789abcdef"[value % base] + buf;
}
更新:(2005/02/11)

Ray-Yuan Sheu发邮件给我,他提出了一个更新版本:做了更多错误检测,例如基底base越界、负整数等。

更新:(2005/04/08)

Rodrigo de Salvo Braz指出了一个bug:当输入为0时没有返回。现在函数返回0。Luc Gallant也指出了这个bug。

std::string version 0.2

/*** C++ version std::string style "itoa":*/
std::string itoa(int value, unsigned int base) {const char digitMap[] = "0123456789abcdef";std::string buf;// Guard:if (base == 0 || base > 16) {// Error: may add more trace/log output herereturn buf;}// Take care of negative int:std::string sign;int _value = value;// Check for case when input is zero:if (_value == 0) return "0";if (value < 0) {_value = -value;sign = "-";}// Translating number to string with base:for (int i = 30; _value && i ; --i) {buf = digitMap[ _value % base ] + buf;_value /= base;}return sign.append(buf);}
更新:(2005/05/07)

Wes Garland指出lltostr函数在Solaris和其他linux变体中存在。函数应该返回long long的char *形式处理多种数基。还有针对无符号数值的ulltostr函数。

更新:(2005/05/30)

John Maloney指出了之前函数的多个问题。一个主要问题是函数包含大量栈分配。他建议尽可能移除栈分配以加快算法速度。char* 版本比上述的代码快至少10倍。新版本的std::string比原来的快3倍。尽管char*版本更快,但是你必须检查以确保为函数输出分配了足够的空间。


std::string version 0.3

/*** C++ version std::string style "itoa":*/
std::string itoa(int value, int base) {enum { kMaxDigits = 35 };std::string buf;buf.reserve( kMaxDigits ); // Pre-allocate enough space.// check that the base if validif (base < 2 || base > 16) return buf;int quotient = value;// Translating number to string with base:do {buf += "0123456789abcdef"[ std::abs( quotient % base ) ];quotient /= base;} while ( quotient );// Append the negative sign for base 10if ( value < 0 && base == 10) buf += '-';std::reverse( buf.begin(), buf.end() );return buf;
}

char *version 0.2

/*** C++ version char* style "itoa":*/
char* itoa( int value, char* result, int base ) {// check that the base if validif (base < 2 || base > 16) { *result = 0; return result; }char* out = result;int quotient = value;do {*out = "0123456789abcdef"[ std::abs( quotient % base ) ];++out;quotient /= base;} while ( quotient );// Only apply negative sign for base 10if ( value < 0 && base == 10) *out++ = '-';std::reverse( result, out );*out = 0;return result;
}
更新:(2006/10/15)

Luiz Gon?lves告诉我:尽管itoa不是ANSI标准函数,但是该函数来自很多开发包并且被写进了很多教科书。他提出了一个来自于Kernighan & Ritchie'sAnsi C的完全基于ANSI C的版本。基底base错误通过返回空字符来表述,并且没有分配内存。这个std::string版本和C++的char *itoa()版本在下方提供,做了一些细微的修改。

译注:下面的方法是最容易想到的:

/*** Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C":*/
void strreverse(char* begin, char* end) {char aux;while(end>begin)aux=*end, *end--=*begin, *begin++=aux;
}void itoa(int value, char* str, int base) {static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";char* wstr=str;int sign;// Validate baseif (base<2 || base>35){ *wstr='\0'; return; }// Take care of signif ((sign=value) < 0) value = -value;// Conversion. Number is reversed.do {*wstr++ = num[value%base];} while(value/=base);if(sign<0) *wstr++='-';*wstr='\0';// Reverse stringstrreverse(str,wstr-1);
}/*** Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C"* with slight modification to optimize for specific architecture:*/void strreverse(char* begin, char* end) {char aux;while(end>begin)aux=*end, *end--=*begin, *begin++=aux;
}void itoa(int value, char* str, int base) {static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";char* wstr=str;int sign;div_t res;// Validate baseif (base<2 || base>35){ *wstr='\0'; return; }// Take care of signif ((sign=value) < 0) value = -value;// Conversion. Number is reversed.do {res = div(value,base);*wstr++ = num[res.rem];}while(value=res.quot);if(sign<0) *wstr++='-';*wstr='\0';// Reverse stringstrreverse(str,wstr-1);
}

更新:(2009/07/08)

过去一年我收到了一些改进std::string和char *版本的代码。我最终有时间测试了这些代码。在std::string版本中,Brian Hunt建议将reverse移到base的检查之后,保存内存分配。这样可以加快速度。

std::string version 0.4

/*** C++ version 0.4 std::string style "itoa":*/std::string itoa(int value, int base) {std::string buf;// check that the base if validif (base < 2 || base > 16) return buf;enum { kMaxDigits = 35 };buf.reserve( kMaxDigits ); // Pre-allocate enough space.int quotient = value;// Translating number to string with base:do {buf += "0123456789abcdef"[ std::abs( quotient % base ) ];quotient /= base;} while ( quotient );// Append the negative signif ( value < 0) buf += '-';std::reverse( buf.begin(), buf.end() );return buf;}

还有一些针对char*版本的建议。Fernando Corradi提议使用abs()因为仅仅使用一次,不使用取余操作(%)而是通过手动计算除数。这样可以加快速度:

char  *version 0.3

	/*** C++ version 0.3 char* style "itoa":*/char* itoa( int value, char* result, int base ) {// check that the base if validif (base < 2 || base > 16) { *result = 0; return result; }char* out = result;int quotient = abs(value);do {const int tmp = quotient / base;*out = "0123456789abcdef"[ quotient - (tmp*base) ];++out;quotient = tmp;} while ( quotient );// Apply negative signif ( value < 0) *out++ = '-';std::reverse( result, out );*out = 0;return result;}

char* version 0.4

Lukás Chmela重写了代码,该函数不再有“最小负数”bug

/*** C++ version 0.4 char* style "itoa":* Written by Lukás Chmela* Released under GPLv3.*/char* itoa(int value, char* result, int base) {// check that the base if validif (base < 2 || base > 36) { *result = '\0'; return result; }char* ptr = result, *ptr1 = result, tmp_char;int tmp_value;do {tmp_value = value;value /= base;*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789
abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];} while ( value );// Apply negative signif (tmp_value < 0) *ptr++ = '-';*ptr-- = '\0';while(ptr1 < ptr) {tmp_char = *ptr;*ptr--= *ptr1;*ptr1++ = tmp_char;}return result;}

最新版本

下面是最新版本的itoa,你可以根据喜好选择char*或std::string版本。我没有将基于Kernighan & Ritchie的版本放在这个部分,因为我不确定其版权的状态。然而,下列函数已经被上述提到的人开发并且是可以使用的。

std::string version 0.4

/*** C++ version 0.4 std::string style "itoa":* Contributions from Stuart Lowe, Ray-Yuan Sheu,* Rodrigo de Salvo Braz, Luc Gallant, John Maloney* and Brian Hunt*/std::string itoa(int value, int base) {std::string buf;// check that the base if validif (base < 2 || base > 16) return buf;enum { kMaxDigits = 35 };buf.reserve( kMaxDigits ); // Pre-allocate enough space.int quotient = value;// Translating number to string with base:do {buf += "0123456789abcdef"[ std::abs( quotient % base ) ];quotient /= base;} while ( quotient );// Append the negative signif ( value < 0) buf += '-';std::reverse( buf.begin(), buf.end() );return buf;}

char* version 0.4

/*** C++ version 0.4 char* style "itoa":* Written by Lukás Chmela* Released under GPLv3.*/char* itoa(int value, char* result, int base) {// check that the base if validif (base < 2 || base > 36) { *result = '\0'; return result; }char* ptr = result, *ptr1 = result, tmp_char;int tmp_value;do {tmp_value = value;value /= base;*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789
abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];} while ( value );// Apply negative signif (tmp_value < 0) *ptr++ = '-';*ptr-- = '\0';while(ptr1 < ptr) {tmp_char = *ptr;*ptr--= *ptr1;*ptr1++ = tmp_char;}return result;}

性能对比

我已经对itoa的各个版本做了测试,研究其转换-32768到32768之间整数,基底在2到20之间时所需要的平均时间(代码仅仅在基底最高位16有效,因此其余的base仅仅是作为测试)。测试结果如下表所示:

functionrelative time
char* style "itoa" (v 0.2)
char* itoa(int value, char* result, int base)
1.0
(XP, Cygwin, g++)
char* style "itoa" (v 0.3)
char* itoa(int value, char* result, int base)
0.93
char* style "itoa" (v 0.4)
char* itoa(int value, char* result, int base)
0.72
Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C" with modification to optimize for specific architecture
void itoa(int value, char* str, int base)
0.92
std::string style "itoa" (v 0.3)
std::string itoa(int value, int base)
41.5
std::string style "itoa" (v 0.4)
std::string itoa(int value, int base)
40.8
如果有人有改进或更好的解决方法,请通知我。我的邮件地址信息可以在 我的博客中找到。



这篇关于GCC下itoa函数的演变:itoa with GCC的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1113683

相关文章

MySQL 中的 CAST 函数详解及常见用法

《MySQL中的CAST函数详解及常见用法》CAST函数是MySQL中用于数据类型转换的重要函数,它允许你将一个值从一种数据类型转换为另一种数据类型,本文给大家介绍MySQL中的CAST... 目录mysql 中的 CAST 函数详解一、基本语法二、支持的数据类型三、常见用法示例1. 字符串转数字2. 数字

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

MySQL count()聚合函数详解

《MySQLcount()聚合函数详解》MySQL中的COUNT()函数,它是SQL中最常用的聚合函数之一,用于计算表中符合特定条件的行数,本文给大家介绍MySQLcount()聚合函数,感兴趣的朋... 目录核心功能语法形式重要特性与行为如何选择使用哪种形式?总结深入剖析一下 mysql 中的 COUNT

MySQL 中 ROW_NUMBER() 函数最佳实践

《MySQL中ROW_NUMBER()函数最佳实践》MySQL中ROW_NUMBER()函数,作为窗口函数为每行分配唯一连续序号,区别于RANK()和DENSE_RANK(),特别适合分页、去重... 目录mysql 中 ROW_NUMBER() 函数详解一、基础语法二、核心特点三、典型应用场景1. 数据分

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Python get()函数用法案例详解

《Pythonget()函数用法案例详解》在Python中,get()是字典(dict)类型的内置方法,用于安全地获取字典中指定键对应的值,它的核心作用是避免因访问不存在的键而引发KeyError错... 目录简介基本语法一、用法二、案例:安全访问未知键三、案例:配置参数默认值简介python是一种高级编

python 常见数学公式函数使用详解(最新推荐)

《python常见数学公式函数使用详解(最新推荐)》文章介绍了Python的数学计算工具,涵盖内置函数、math/cmath标准库及numpy/scipy/sympy第三方库,支持从基础算术到复杂数... 目录python 数学公式与函数大全1. 基本数学运算1.1 算术运算1.2 分数与小数2. 数学函数

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五