I have a completed assignment that required me to convert from base 10 to any base (up to 16) the user specifies. My completed program is below. However I'd like to change it up to convert from any input base to any requested base. I am not sure how to do that. I am thinking about changing the input to a char string, and then manipulating the string using string functions such as strlen, string::rbegin, etc to then do the conversion. However, I don't know if that would work for what I am trying to accomplish. This assignment has already been submitted and graded so don't think I am doing this as something to turn in, just my own personal knowledge. If anyone can help I would appreciate it. Thanks.
Header File:
1 2 3 4 5 6 7 8 9 10 11
class InVal
{
private:
int num;
int base;
public:
void PrintAsBase(int base);
InVal();
void init_val(int, int);
};
#include <iostream>
#include <cstring>
#include <cmath>
#include "base.h"
usingnamespace std;
int main()
{
int base;
int num;
InVal num_c;
cout << "Please enter the number you wish to convert:\n";
cin >> num;
if (cin.fail())
{
cout << "This is not a valid input.\n\n";
return 1;
}
cout << "Please enter the base you wish to convert to:\n";
cin >> base;
if (cin.fail())
{
cout << "This is not a valid input.\n\n";
return 1;
}
if (base < 2 || base > 16)
{
cout << "You have entered a base that is outside of\n"
<< "the valid range.\n\n";
return 1;
}
num_c.init_val(num,10);
cout << "Your number is: ";
num_c.PrintAsBase(base);
}
To convert form any1 base to any2, I suggest you first convert from any1 to ??? and then from ??? to any2. ??? is because you probably think it is 10 though it is more like 2. But really, it makes no difference what that base is.
For example, converting 10010 in base 2 to base 11:
??? = 0*20 + 1*21 + 0*22 + 0*23 + 1*24
(??? = 18 in base 10)
(??? / 11) % 11 = 1
??? % 11 = 7
so the result is 17
@ hamsterman - That's why I was thinking about taking the input as a character string. Because in order to use the pow function, I would have to reverse the input and go from there. It seems simple enough in my head, but writing it out and making it work is something a little different.
@coder777 - I will try that and see what happens.
I figure I can ask for the base they are inputting, but (and I am probably very wrong here) but regardless of the base the user inputs I should be able to convert using the pow function as described. The reason I say this is that if I input something in base 6 and ask for base 7, all I am really doing with the input is taking each of those digits and raising them to 7^0, 7^1, 7^2, etc. The input base or asking them for it doesn't change that does it? Like I said, I am probably very wrong here... Heh heh.