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中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 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

Python中bisect_left 函数实现高效插入与有序列表管理

《Python中bisect_left函数实现高效插入与有序列表管理》Python的bisect_left函数通过二分查找高效定位有序列表插入位置,与bisect_right的区别在于处理重复元素时... 目录一、bisect_left 基本介绍1.1 函数定义1.2 核心功能二、bisect_left 与

java中BigDecimal里面的subtract函数介绍及实现方法

《java中BigDecimal里面的subtract函数介绍及实现方法》在Java中实现减法操作需要根据数据类型选择不同方法,主要分为数值型减法和字符串减法两种场景,本文给大家介绍java中BigD... 目录Java中BigDecimal里面的subtract函数的意思?一、数值型减法(高精度计算)1.

C++/类与对象/默认成员函数@构造函数的用法

《C++/类与对象/默认成员函数@构造函数的用法》:本文主要介绍C++/类与对象/默认成员函数@构造函数的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录名词概念默认成员函数构造函数概念函数特征显示构造函数隐式构造函数总结名词概念默认构造函数:不用传参就可以

C++类和对象之默认成员函数的使用解读

《C++类和对象之默认成员函数的使用解读》:本文主要介绍C++类和对象之默认成员函数的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、默认成员函数有哪些二、各默认成员函数详解默认构造函数析构函数拷贝构造函数拷贝赋值运算符三、默认成员函数的注意事项总结一

Python函数返回多个值的多种方法小结

《Python函数返回多个值的多种方法小结》在Python中,函数通常用于封装一段代码,使其可以重复调用,有时,我们希望一个函数能够返回多个值,Python提供了几种不同的方法来实现这一点,需要的朋友... 目录一、使用元组(Tuple):二、使用列表(list)三、使用字典(Dictionary)四、 使

PyTorch中cdist和sum函数使用示例详解

《PyTorch中cdist和sum函数使用示例详解》torch.cdist是PyTorch中用于计算**两个张量之间的成对距离(pairwisedistance)**的函数,常用于点云处理、图神经网... 目录基本语法输出示例1. 简单的 2D 欧几里得距离2. 批量形式(3D Tensor)3. 使用不

MySQL 字符串截取函数及用法详解

《MySQL字符串截取函数及用法详解》在MySQL中,字符串截取是常见的操作,主要用于从字符串中提取特定部分,MySQL提供了多种函数来实现这一功能,包括LEFT()、RIGHT()、SUBST... 目录mysql 字符串截取函数详解RIGHT(str, length):从右侧截取指定长度的字符SUBST

Kotlin运算符重载函数及作用场景

《Kotlin运算符重载函数及作用场景》在Kotlin里,运算符重载函数允许为自定义类型重新定义现有的运算符(如+-…)行为,从而让自定义类型能像内置类型那样使用运算符,本文给大家介绍Kotlin运算... 目录基本语法作用场景类对象数据类型接口注意事项在 Kotlin 里,运算符重载函数允许为自定义类型重