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

相关文章

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数

python中的高阶函数示例详解

《python中的高阶函数示例详解》在Python中,高阶函数是指接受函数作为参数或返回函数作为结果的函数,下面:本文主要介绍python中高阶函数的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录1.定义2.map函数3.filter函数4.reduce函数5.sorted函数6.自定义高阶函数

Python中的sort方法、sorted函数与lambda表达式及用法详解

《Python中的sort方法、sorted函数与lambda表达式及用法详解》文章对比了Python中list.sort()与sorted()函数的区别,指出sort()原地排序返回None,sor... 目录1. sort()方法1.1 sort()方法1.2 基本语法和参数A. reverse参数B.

Python函数的基本用法、返回值特性、全局变量修改及异常处理技巧

《Python函数的基本用法、返回值特性、全局变量修改及异常处理技巧》本文将通过实际代码示例,深入讲解Python函数的基本用法、返回值特性、全局变量修改以及异常处理技巧,感兴趣的朋友跟随小编一起看看... 目录一、python函数定义与调用1.1 基本函数定义1.2 函数调用二、函数返回值详解2.1 有返

Python Excel 通用筛选函数的实现

《PythonExcel通用筛选函数的实现》本文主要介绍了PythonExcel通用筛选函数的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录案例目的示例数据假定数据来源是字典优化:通用CSV数据处理函数使用说明使用示例注意事项案例目的第一

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

GO语言中函数命名返回值的使用

《GO语言中函数命名返回值的使用》在Go语言中,函数可以为其返回值指定名称,这被称为命名返回值或命名返回参数,这种特性可以使代码更清晰,特别是在返回多个值时,感兴趣的可以了解一下... 目录基本语法函数命名返回特点代码示例命名特点基本语法func functionName(parameters) (nam

Python Counter 函数使用案例

《PythonCounter函数使用案例》Counter是collections模块中的一个类,专门用于对可迭代对象中的元素进行计数,接下来通过本文给大家介绍PythonCounter函数使用案例... 目录一、Counter函数概述二、基本使用案例(一)列表元素计数(二)字符串字符计数(三)元组计数三、C

Python中的filter() 函数的工作原理及应用技巧

《Python中的filter()函数的工作原理及应用技巧》Python的filter()函数用于筛选序列元素,返回迭代器,适合函数式编程,相比列表推导式,内存更优,尤其适用于大数据集,结合lamb... 目录前言一、基本概念基本语法二、使用方式1. 使用 lambda 函数2. 使用普通函数3. 使用 N