Is it possible to have one algorithm to convert to any base (at least 2-12) starting from base 10, or will i need a separate one for each base?
Printable View
Is it possible to have one algorithm to convert to any base (at least 2-12) starting from base 10, or will i need a separate one for each base?
First outline your algorithm(s) for converting to bases 2 and 3.
Well, I have base 2, but it's 2am so I'll work on base 3 tomorrow :p
Code:void to_binary(unsigned long num, int base) {
/* recursive function */
int remainder;
remainder = num % 2;
if (num >= 2)
to_binary(num / 2);
putchar( remainder ? '1' : '0');
return;
}
After working on base 3, compare the algorithms and see how you can combine them. For bases no greater than 10 it is straightforward, but you'll have to think a little about numerals for bases above 10 (but don't worry, it is still easy).
Yea, it wasn't so difficult I suppose. I made it general for any base, but I don't know how all the number systems actually work. I guess as long as they follow the same rules as hex then this would work.
Any suggestions?
Code:#include <stdio.h>
void to_base_n(unsigned long, int);
int main(void) {
unsigned long number;
int base;
printf("Enter an integer and a desired base (q to quit):\n");
while (scanf("%lu %d", &number, &base) == 2) {
printf("Base-%d Equivalent: ", base);
to_base_n(number, base);
putchar('\n');
printf("Enter an integer and a desired base (q to quit):\n");
}
printf("Done.\n");
return 0;
}
void to_base_n(unsigned long num, int base) {
/* recursive function */
int remainder = num % base;
if (num >= base)
to_base_n(num / base, base);
if (remainder > 10)
remainder += 54;
else
remainder += 48;
putchar(remainder);
return;
}