Page 1 of 1

Having a problem in converting integers into text

Posted: Wed Oct 24, 2007 5:48 pm
by Pyrofan1

Code: Select all

char *strcpy(char *dest, const char *src)
{
   const char *p;
   char *q; 
 
   for(p = src, q = dest; *p != '\0'; p++, q++)
     *q = *p;
 
   *q = '\0';
 
   return dest;
}

void itoa(int n,char number[])
{
    int i, sign, j;
    char *t;
    if ((sign = n) < 0)  /* record sign */
        n = -n;          /* make n positive */
    i = 0;
    do {       /* generate digits in reverse order */
        number[i++] = n % 10 + '0';   /* get next digit */
    } while ((n /= 10) > 0);     /* delete it */
    if (sign < 0)
        number[i++] = '-';
    number[i] = '\0';
    
	strcpy(t,number);
	for(i = 0 , j = strlen(number) - 1 ; j >= 0 ; i++, j--)
	{
     		number[i] = *(t + j);
	}
} 
okay my itoa function works as in that it can turn an integer into text, but this part

Code: Select all

strcpy(t,number);
	for(i = 0 , j = strlen(number) - 1 ; j >= 0 ; i++, j--)
	{
     		number[i] = *(t + j);
	}
the code that reverses the number so that it is the right number does not work. what i mean by that is when i leave it in the function leaves nothing in number[], but when i comment it out it works fine (besides the fact that the number is backward). i have tried everything that i could think of, but i can not get this code to work.

Posted: Wed Oct 24, 2007 8:49 pm
by thewonderidiot
Check your strlen() function. I think that it's the problem. I put your exact code into my own OS (except I changed the function names to pfitoa and pfstrcopy to avoid conflicts). It worked fine when I ran this:

Code: Select all

char atest[50] = {0};
int btest = 42;
pfitoa(btest,atest);
printf("%s\n",atest);
And seeing as the strlen() is the ONLY difference between the code I ran and the code you posted... that might be the problem. :)

Posted: Wed Oct 24, 2007 9:18 pm
by nick8325
You don't seem to initialize t anywhere. Does it help if you write

Code: Select all

char t[21];
instead? (The string representation of a 64-bit integer should fit in 21 characters, including '-' and the 0-terminator.)

Posted: Wed Oct 24, 2007 9:53 pm
by Pyrofan1
your suggestion didn't help nick
here is my strlen function

Code: Select all

int strlen(char *str)
{
	int len;
	while(*str!=NULL)
	{
		len++;
	}
	return len;
}

Posted: Wed Oct 24, 2007 10:51 pm
by nick8325
You need to initialize len, too: int len = 0. Otherwise, it will have some random value.

Posted: Wed Oct 24, 2007 10:56 pm
by nick8325
Oh, your loop in strlen() should increment str as well as len. Otherwise, it'll run forever.

Posted: Wed Oct 24, 2007 11:00 pm
by Pyrofan1
it's always those little mistakes that get you. thanks for your help.