Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

write a program in C++that converts number bases. In particular, the program wil

ID: 3534521 • Letter: W

Question

write a program in C++that converts number bases. In particular, the program will perform the following tasks:

1)      The program should accept entries in decimal, binary, and octal <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

2)      The program will convert numbers entered in decimal, binary and octal to other bases

3)      The program should be able to convert to other bases, other than bases 2, 8, and 16

4)      The program must work in reverse as well; e.g. if you can convert a number from decimal to binary, you should also be able to convert from binary to decimal.

Explanation / Answer

USe the following two methods to convert any base to base 10. And From Base 10 to any other base int to_dec(char* value, int starting_base) { int return_value = 0; for (char* cur = value + strlen(value) - 1; cur >= value; cur--) { // assuming chars are ascii/utf: 0-9=48-57, A-F=65-70 // faster than loop int inval = *cur - 48; if (inval > 9) { inval = *cur - 55; if (inval > 15) { // throw input error } } if (inval < 0) { // throw input error } if (inval >= starting_base) { // throw input error } // now the simple calc return_value *= starting_base; return_value += inval; } return return_value; } //From base 10 to any other base std::string from_dec(int n, int base) { std::string result; bool is_negative = n < 0; if (is_negative) { n = - n; } while (n != 0) { result = DIGITS[n % base] + result; n /= base; } if (is_negative) { result = '-' + result; } return result; }