My_itoa在C++中的我的itoa(数值转标准字符串)函数
来源:互联网 发布:网络团队招人广告词 编辑:程序博客网 时间:2024/05/20 00:52
itoa with GCC
- Introduction
- Credits
- Development
- Latest Versions
- Performance Comparison
How do I use itoa() with GCC?
Arrgghh C/C++! It would appear that itoa()
isn't ANSI C standard and doesn't work with GCC on Linux (at least the version I'm using). Things like this are frustrating especially if you want your code to work on different platforms (Windows/Linux/Solaris/whatever).
Many people say that you should just use sprintf to write to a character string but that doesn't allow for one of the features of itoa(); the ability to write in a base other than 10. This page contains a series of evolving versions of an itoa implementation. The oldest are near the top and the latest at the bottom. Please make sure that you use the latest version.
Credits
Before we go any further, I would like to say thanks to the people that contributed to the solutions below. This function has been put together by contributions from Stuart Lowe (that's me), Robert Jan Schaper, Ray-Yuan Sheu, Rodrigo de Salvo Braz, Wes Garland, John Maloney, Brian Hunt, Fernando Corradi and Lukás Chmela.
Development
Below is an early version described by Robert Jan Schaper on 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];}
This doesn't quite look like the implementation I am used to which is more likeitoa(int value, char* buffer, int radix)
. In the end I have made my own version which uses a std::string instead of a character 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;}
Update: (2005/02/11)
Ray-Yuan Sheu sent me an email with an improved version which does a bit more error checking for things like a base that is out of range and for negative integers.
Update: (2005/04/08)
Rodrigo de Salvo Braz spotted a bug that meant nothing was returned when the input was zero. It now returns "0". This bug has also been spotted by Luc Gallant.
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);}
Update: (2005/05/07)
Wes Garland says that lltostr
exists under Solaris and several other unices. It should return achar *
of a long long in multiple number bases. There is also ulltostr
for unsigned values.
Update: (2005/05/30)
John Maloney has pointed out various problems with the previous implementation. One of the major issues was the amount of heap allocation going on. He suggested that a lot of this be removed to speed up the algorithm. Below are two versions based on his excellent suggestions. The char*
version is at least 10 times faster than the code above. The newstd::string
version is 3 times faster than before. Although the char*
version is faster, you should check that you have allocated enough space to hold the output.
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;}
Update: (2006/10/15)
Luiz Gon?lves tells me that although not an ANSI standard, itoa comes in many packages and it is written in many textbooks. He suggests a version written in pure ANSI C based on a version from Kernighan & Ritchie'sAnsi C. A base error is reported by the return of an empty string but the function does no checks of sizes and no allocations. This version is provided below along with a slightly modified version (architecture specific tweaks), thestd::string
version and the C++ char* itoa()
version.
/** * 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);}
Update: (2009/07/08)
Over the past year I've had a few suggestions for improvements to both the std::string and char* versions of the code. I've finally had time to test them.
In the std::string version, Brian Hunt suggested to move the reserve after the base check to save memory allocations. This does speed things up a little.
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;}
There have also been several suggestions for improvements to the char* version of the code. Fernando Corradi suggested moving the abs() so that it is used only once and not using the modulus operator (%) but rather calculating it by hand saving a division. This does speed things up a little:
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;}
However, Lukás Chmela has re-written the code so that it doesn't have a "most negative number" bug:
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++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [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;}
Latest Versions
Below are the latest versions of the itoa function using either char*
orstd::string
as you prefer. I haven't included the Kernighan & Ritchie based versions in this section because I'm not sure what the copyright status is for those. However, the functions below have been developed by the people mentioned on this page and are available for use.
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++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [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;}
Performance Comparsion
I've done some testing of the versions of itoa by finding the average time required to perform conversions, of the integers in the range -32768 to 32767, in every base from base 2 to base 20 (the code only works up to base 16 so the extra bases are just there as tests). The summary is presented in the following table:
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.93char* style "itoa" (v 0.4)char* itoa(int value, char* result, int base)
0.72Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C" with modification to optimize for specific architecturevoid itoa(int value, char* str, int base)
0.92std::string style "itoa" (v 0.3)std::string itoa(int value, int base)
41.5std::string style "itoa" (v 0.4)std::string itoa(int value, int base)
40.8If anyone has any improvements or better solutions, please let me know. My email address can be worked out from information on my blog:
http://blog.csdn.net/aw344/
- My_itoa在C++中的我的itoa(数值转标准字符串)函数
- C语言整数转字符串(itoa()函数)小练习
- C语言整数转字符串itoa函数
- atoi() 函数与 itoa() 函数:字符串与数值之间的转换
- itoa不是c语言标准函数
- my_itoa.c
- itoa、atoi 整型转字符串、字符串转整型的函数
- C语言的本质(26)——C标准库之数值字符串转换
- 标准C语言中的字符串处理函数
- 标准C语言中的字符串处理函数
- 标准c中的字符串处理函数
- itoa 函数编写,赏析,simple_itoa,整数转字符串,itoa自定义
- C函数的实现(strcpy,atoi,atof,itoa,reverse)
- 我自己归纳的C标准(C99)函数.
- c语言标准字符串函数的使用
- 数字转换为字符串(itoa函数)
- C函数atoi,itoa的实现代码
- [C++] Linux下的itoa函数
- webservice 比较
- DRAM BRANK
- 50个sql高级查询示范
- Struts2中的struts.multipart.saveDir的配置
- /ERROR 1045 (28000): Access denied for user 'wwn'@'localhost' (using password: YES)
- My_itoa在C++中的我的itoa(数值转标准字符串)函数
- centos5.8 安装oracle10g
- java读取文件的四种方法总结
- windows下boost,pthread,clapack,jpeg,gsl的配置
- 通向架构师的道路(第十五天)IBM Websphere的安装与优化
- 黑马程序员------JAVA面向对象
- Linux IPC总结(全)
- C++类中的static数据成员,static成员函数
- boost::property_tree