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?
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?
Last edited by kbat82; 12-10-2008 at 01:15 AM. Reason: added "starting from base 10"
First outline your algorithm(s) for converting to bases 2 and 3.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Well, I have base 2, but it's 2am so I'll work on base 3 tomorrow
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).
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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; }
Last edited by kbat82; 12-10-2008 at 12:54 PM. Reason: noticed an error in the code :)