This code is almost perfect. The only problem occurs (commented in code below). The problem does not occur if T is an int and n is int_min. Little help please. There is a solution to this because ostringstream gets it right.
PHP Code:#define int64_max 9223372036854775807LL
#define int64_min (-int64_max-1)
template <typename T>
aStr IntToStr(T n, uint radix= 10)
{
if(!n)
{
return "0";
}
else
{
bool neg= n < 0;
if(neg)
{
n= -n;
MB(n); //when T is __int64 and n is int64_min, n stays as int64_min!
}
const uint bits= sizeof(T)*8;
char buf[bits];
// Set chars from the end of the buffer
char* ptr= &buf[bits-1];
*ptr= 0; //terminating NULL
while(n > 0)
{
--ptr;
//*ptr= itoaChars[n%radix]; //this works too
*ptr= n%radix+'0';
n /= radix;
}
if(neg)
{
--ptr;
*ptr= '-';
}
return aStr(ptr);
}
}




Reply With Quote