In: Computer Science
c++ programming:
Write a function called baseConverter(string number, int startBase, int endBase) in c++ which converts any base(startBase) to another (endBase) by first converting the start base to decimal then to the end base. Do not use library. (bases 1-36 only)
Given below is the code for the question. Please do rate the answer if it helped. Thank you.
#include <iostream>
using namespace std;
string baseConverter(string number, int startBase, int
endBase)
{
long decimal = 0;
char c;
int val, rem;
int power = 1;
string result = "";
//convert to decimal
for(int i = number.size() - 1; i >= 0; i--){
c = number[i];
if(c >= '0' && c <=
'9')
val = c -
'0';
else if(c >= 'A' && c
<= 'Z')
val = c - 'A' +
10;
else if(c >= 'a' && c
<= 'z')
val = c - 'a' +
10;
decimal = decimal + val *
power;
power = power * startBase;
}
//convert from decimal to endBase by repeated division
and get remainders
while(decimal > 0){
rem = decimal % endBase;
decimal = decimal / endBase;
if(rem >= 10)
c = 'A' + (rem -
10);
else
c = '0' +
rem;
result = c + result;
}
if(result == "")
result = "0";
return result;
}
int main(){
cout << baseConverter("ABCD", 16, 10) <<
endl;
}