int my_itoa(char* str, int num) {
int i, neg = 0, length = 1, x = 0;
if(str != NULL) {
if(num < 0) {
neg = num;
num = -num;
}
for(i = num / 10; i > 0 ; i /= 10) {
length++;
}
for(i = length - 1; i >= 0; i--) {
if(neg < 0) {
str[0] = '-';
neg = 1;
}
str[i + neg] = (num % 10) + '0';
num /= 10;
}
str[length + neg] = '\0';
x = 1;
}
return x;
}
Tuesday, January 25, 2011
Making an int into a char* (string) Part 2.1
I realized afterwards that I forgot to ensure my function would work with negative numbers as well as positive. I have added a few lines to remedy this.
Labels:
open-source
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment