I'm trying to convert from some base (2-9) to base 10. The way this has to be done involves a lot of conversion between strings and integers because the function has to spit out a string, but it takes three arguments: the number to convert, the starting base, and the end base.
Anyways, here are some of the results I get when trying to convert various numbers from base 2 to base 10:
Number Result
11 2
100 4
101 4
110 4
111 4
1000 8
1001 8
1010 8
1011 8
1100 8
As you can see, a bit of a pattern has emerged. It's only converting the first digit to base ten and ignoring the rest. I'm not really sure why this is happening. Here is the code that is doing it:
char* baseConversion(int number, int inBase, int toBase)
{
char tempString[20];
if(number==0)
{
tempString[0] = 0;
return tempString;
}
if(toBase == 10)
{
sprintf(tempString, "%d", number);
char tempString2[] = {tempString[0]};
int tempNumber = (atoi(tempString2)*((int)pow((float)inBase,(float)strlen(tempString)-1.0))+atoi(baseConversion(atoi(tempString+1), inBase, 10)));
sprintf(tempString, "%d", tempNumber);
return tempString;
}
}
Maybe it's something wrong with my algorithm, but I tried it on paper and it seems to work. Thanks.