My quick 15 minute test program.
Note: My program only does base 2 to 10; but, I think this just means the code in fromBaseTen into a function that returns a char array. This would likely take another 15 minutes to half for me to do. But, I have no idea if you know malloc or static char arrays.
I used this code in my baseConversion function; but, it will likely need moved to the new fromBaseTen function.
Code:
char* baseConversion(int num, int base, int newBase)
{
static char result_string[MAX_RESULT_LENGTH+1] = {0};
snprintf(result_string, MAX_RESULT_LENGTH, "%d", fromBaseTen( toBaseTen( num, base ), newBase ));
return result_string;
}
Code:
#include <stdio.h>
#include <stdlib.h>
/* Max number of charators in the result of baseConversion */
#define MAX_RESULT_LENGTH 32
char* baseConversion(int num, int base, int newBase);
int toBaseTen( int num, int base );
int fromBaseTen( int num, int base );
int main()
{
printf("Testing!\n");
printf("toBaseTen(0,8) := %d\n", toBaseTen(0,8));
printf("fromBaseTen(0,8) := %d\n", fromBaseTen(0,8));
printf("toBaseTen(10,8) := %d\n", toBaseTen(10,8));
printf("fromBaseTen(8,8) := %d\n", fromBaseTen(8,8));
printf("toBaseTen(17,8) := %d\n", toBaseTen(17,8));
printf("fromBaseTen(15,8) := %d\n", fromBaseTen(15,8));
printf("toBaseTen(127,8) := %d\n", toBaseTen(127,8));
printf("fromBaseTen(87,8) := %d\n", fromBaseTen(87,8));
printf("baseConversion(127, 8, 10) := %s\n", baseConversion(127, 8, 10));
printf("baseConversion(127, 8, 2) := %s\n", baseConversion(127, 8, 2));
return 0;
}
Code:
Testing!
toBaseTen(0,8) := 0
fromBaseTen(0,8) := 0
toBaseTen(10,8) := 8
fromBaseTen(8,8) := 10
toBaseTen(17,8) := 15
fromBaseTen(15,8) := 17
toBaseTen(127,8) := 87
fromBaseTen(87,8) := 127
baseConversion(127, 8, 10) := 87
baseConversion(127, 8, 2) := 1010111
Tim S.
FYI: I am NOT posting the code that takes real thought because the only way to learn it is to figure it out yourself.