I have been trying to find the correct way to do this for a while now:
I need to convert either binary to all the bases but I keep running into errors.
This worked to convert binary to decimal, but when I change the power from 2 to another number it wont convert to the different base. Im not sure why this is.
1 2 3 4
reverse(userNumber.begin(), userNumber.end());
for (int i = 0; i < userNumber.size(); ++i) {
decimal += (int(userNumber[i]) - 48)*pow(2, i);
}
I have tried many different solutions to this problem but I cannot find the correct one.
I have also tried to convert the string to an array to try to make it easier on myself, but had no luck.
Does any one have any words of wisdom that could be passed my way.
All help will be appreciated
#include <cmath>
#include <algorithm>
#include <iostream>
usingnamespace std;
int main()
{
int base=0;
string userNumber;
int decimal=0;
cout<<"Enter the base of the number followed by the number "<<endl;
cout<<"In the same line enter the bases you want it to be converted to"<<endl;
cin>>base>>userNumber;
//convert to dec
reverse(userNumber.begin(), userNumber.end());
for (int i = 0; i < userNumber.size(); ++i) {
decimal += (int(userNumber[i]) - 48)*pow(2, i);
}
switch (base) {
case 2:
cout<<userNumber<<" (Base 2) "<<endl;
break;
case 3:
cout<<decimal<<" (Base 3) "<<endl;
break;
case 4:
cout<<decimal<<" (Base 4) "<<endl;
break;
case 5:
cout<<decimal<<" (Base 5) "<<endl;
break;
case 6:
cout<<decimal<<" (Base 6) "<<endl;
break;
case 7:
cout<<decimal<<" (Base 7) "<<endl;
break;
case 8:
cout<<oct<<decimal<<" (Base 10) "<<endl;
break;
case 9:
cout<<decimal<<" (Base 9) "<<endl;
break;
case 10:
cout<<dec<<decimal<<" (Base 10) "<<endl;
break;
case 11:
cout<<decimal<<" (Base 11) "<<endl;
break;
case 12:
cout<<decimal<<" (Base 12) "<<endl;
break;
case 13:
cout<<decimal<<" (Base 13) "<<endl;
break;
case 14:
cout<<decimal<<" (Base 14) "<<endl;
break;
case 15:
cout<<decimal<<" (Base 15) "<<endl;
break;
case 16:
cout<<hex<<decimal<<" (Base 16) "<<endl;
break;
default:
cout<<"Base is not in range 2-16"<<endl;
return 0;
break;
}
cout<<"Base; "<<base<<" userNumber; "<<userNumber<<endl;
return 0;
}