After searching extensively for a function that would convert integers into visually equivalent strings and finding nothing, I decided to write my own.
The function “ascii” takes three arguments: the integer to be converted, the string to hold the converted integer, and a counter that is meant to be left at 0.
void ascii(int c, char str[], int k) {
if (c <= 9) {
str[k] = c + '0';
}
else if (c >= 10) {
str[k] = c / 10 + '0';
ascii(c % 10, str, k + 1);
}
}
Testing this function with a single-digit number turns up nothing unexpected, but on bigger numbers, things start to get messy. 76 becomes “761”, 765 becomes “|51”, and 7658 becomes “-81”. The more digits the number is comprised of, the less sense I can make out of the resulting string. What gives?
I belive here’s the problem:
The arithmetic operations were inverted. The resulting array must be inverted afterwards (from a different function, that calls the function in the question as a helper), and it must end in a
'\0'char.Alternatively, you could copy the results in the output array in reverse order, but that’s assuming you know beforehand the number of digits.