Thursday, January 27, 2011

Converting Integer to String

I decided to try creating my own version of the Int2Str function. I'm not sure if it's the most efficient way of doing it but it does work from what I've tested. It basically goes through every digit in the number starting from the lowest to the highest digit, converts it as a character, and stores it in the character array. This produces the correct string but unfortunately it's backwards. To combat this I then reverse the character array to get the final correct output.

void Int2Str(char* num, int number) {
int i = -1;
int j = 0;
int k;
char temp;
while (number) {
i++;
num[i] = (char)((number % 10) + 48);
number /= 10;
}
num[i+1] = '\0';

k = (i + 1) / 2;

while (j != k) {
temp = num[j];
num[j] = num[i];
num[i] = temp;
i--;
j++;
}
}