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

相关文章

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

C语言函数递归实际应用举例详解

《C语言函数递归实际应用举例详解》程序调用自身的编程技巧称为递归,递归做为一种算法在程序设计语言中广泛应用,:本文主要介绍C语言函数递归实际应用举例的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录前言一、递归的概念与思想二、递归的限制条件 三、递归的实际应用举例(一)求 n 的阶乘(二)顺序打印

C/C++错误信息处理的常见方法及函数

《C/C++错误信息处理的常见方法及函数》C/C++是两种广泛使用的编程语言,特别是在系统编程、嵌入式开发以及高性能计算领域,:本文主要介绍C/C++错误信息处理的常见方法及函数,文中通过代码介绍... 目录前言1. errno 和 perror()示例:2. strerror()示例:3. perror(

Kotlin 作用域函数apply、let、run、with、also使用指南

《Kotlin作用域函数apply、let、run、with、also使用指南》在Kotlin开发中,作用域函数(ScopeFunctions)是一组能让代码更简洁、更函数式的高阶函数,本文将... 目录一、引言:为什么需要作用域函数?二、作用域函China编程数详解1. apply:对象配置的 “流式构建器”最

Android Kotlin 高阶函数详解及其在协程中的应用小结

《AndroidKotlin高阶函数详解及其在协程中的应用小结》高阶函数是Kotlin中的一个重要特性,它能够将函数作为一等公民(First-ClassCitizen),使得代码更加简洁、灵活和可... 目录1. 引言2. 什么是高阶函数?3. 高阶函数的基础用法3.1 传递函数作为参数3.2 Lambda

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注

C++中函数模板与类模板的简单使用及区别介绍

《C++中函数模板与类模板的简单使用及区别介绍》这篇文章介绍了C++中的模板机制,包括函数模板和类模板的概念、语法和实际应用,函数模板通过类型参数实现泛型操作,而类模板允许创建可处理多种数据类型的类,... 目录一、函数模板定义语法真实示例二、类模板三、关键区别四、注意事项 ‌在C++中,模板是实现泛型编程

kotlin的函数forEach示例详解

《kotlin的函数forEach示例详解》在Kotlin中,forEach是一个高阶函数,用于遍历集合中的每个元素并对其执行指定的操作,它的核心特点是简洁、函数式,适用于需要遍历集合且无需返回值的场... 目录一、基本用法1️⃣ 遍历集合2️⃣ 遍历数组3️⃣ 遍历 Map二、与 for 循环的区别三、高

C语言字符函数和字符串函数示例详解

《C语言字符函数和字符串函数示例详解》本文详细介绍了C语言中字符分类函数、字符转换函数及字符串操作函数的使用方法,并通过示例代码展示了如何实现这些功能,通过这些内容,读者可以深入理解并掌握C语言中的字... 目录一、字符分类函数二、字符转换函数三、strlen的使用和模拟实现3.1strlen函数3.2st

MySQL中COALESCE函数示例详解

《MySQL中COALESCE函数示例详解》COALESCE是一个功能强大且常用的SQL函数,主要用来处理NULL值和实现灵活的值选择策略,能够使查询逻辑更清晰、简洁,:本文主要介绍MySQL中C... 目录语法示例1. 替换 NULL 值2. 用于字段默认值3. 多列优先级4. 结合聚合函数注意事项总结C