Implement the standard I/O function itoa(). The itoa() function constructs a string representation of an integer. The parameters are:
value: the integer to be converted to string representation.
string: points to the buffer that is to hold resulting string.
radix: is the base of the number; must be in the range 2 – 36.
char *itoa(int value, char *string, int radix)
{
{
4 Comments so far
Leave a comment
i think it’s something like this…
int stridx = 0;
for (;;) {
int q, pow = 0;
do {
++pow;
// since q is int it will only contain
// whole part of the quotient
q = value / pow(radix, pow);
} while (q >= radix);
if (q < 10)
string[stridx++] = q + ’0′; // use digits
else
string[stridx++] = q + ‘a’; // use letters
value -= (q * pow(radix, pow));
if (value == 0) {
string[stridx] = ”; // null plug
break;
}
}
By ilya on 03.02.11 1:50 pm | Permalink
This is using C++ syntax
char *itoa(int value, char *string, int radix)
{
// Unfortunately , there is no way to guarantee that string
// is long enough to hold the converted value. The caller
// of this function must guarantee this for us
// Check for negative values.
if (value < 0)
{
*string++ = ‘-’;
}
// Compute number of digits needed
int numDigits = static_cast(log(value)/log(radix));
// Null terminate now so that we don’t forget
string[numDigits] = ”;
// Fill in the string
while (numDigits > 0)
{
// Get the value of the current digit.
int remainder = value % radix;
// Update value for next iteration
value /= radix;
// Convert value into ascii.
char asciiDigit;
if (remainder < 10)
asciiDigit = remainder + ’0′;
else
asciiDigit = remainder + ‘a’;
// Fill in the current digit
*string[numDigits-1] = asciiDigit;
// Update iterator
–numDigits;
}
}
By Simon on 05.11.11 10:51 pm | Permalink
Oops, in my post above, I forgot to get the absolute “value”:
// Check for negative values.
if (value < 0)
{
*string++ = ‘-’;
value *= -1;
}
By Simon on 05.11.11 11:00 pm | Permalink
System::Convert::ToString(val); /snicker
By Potter on 06.02.11 1:30 pm | Permalink
Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.