/**
* 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 base
if (base<2 || base>35){ *wstr='\0'; return; }
// Take care of sign
if ((sign=value) < 0) value = -value;
// Conversion. Number is reversed.
do *wstr++ = num[value%base]; while(value/=base);
if(sign<0) *wstr++='-';
*wstr='\0';
// Reverse string
strreverse(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 base
if (base<2 || base>35){ *wstr='\0'; return; }
// Take care of sign
if ((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 string
strreverse(str,wstr-1);
}
/**
* 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 valid
if (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 10
if ( value < 0 && base == 10) buf += '-';
std::reverse( buf.begin(), buf.end() );
return buf;
}
/**
* C++ version char* style "itoa":
*/
char* itoa( int value, char* result, int base ) {
// check that the base if valid
if (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 10
if ( value < 0 && base == 10) *out++ = '-';
std::reverse( result, out );
*out = 0;
return result;
}
출처 : http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
'컴퓨터 > 언어,프로그래밍' 카테고리의 다른 글
퀵정렬(Quick Sort)이란? (0) | 2009.06.09 |
---|---|
C언어 정수,실수 데이터형 (0) | 2009.06.09 |
itoa - 정수형 데이터를 문자열로 변환하기 (0) | 2009.06.09 |
[본문스크랩] HTML 태그표 총정리 (0) | 2009.06.08 |
자바, 문자열 문자열 나누기 (0) | 2009.06.06 |