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

3.4 Converting base representation. Write a function convertbase which converts

ID: 3894513 • Letter: 3

Question

3.4 Converting base representation. Write a function convertbase which converts a number, represented as a string in one base, to a new string representing that number in a new base. You may assume that the number can be stored in an int without overflow string convertbase (const string& numstr, const int frombase, const int tobase) The character to digitvalue+'0" represent a digit with value digit value is the ASCII character The values of frombase and tobase will always be in the range 2 to 200 inclusive

Explanation / Answer


Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you


#include <iostream>
#include <string>
using namespace std;

string convert(const string& numstr, const int frombase, const int tobase)
{
char ch;
int deci = 0;
int power = 1;
int digitvalue;

//get the decimal value of the number
for(int i = numstr.length() - 1; i >= 0; i--)
{
ch = numstr[i];
digitvalue = ch - '0';
deci = digitvalue * power;
power = power * frombase;
}

//from decimal convert to tobase
string result = "";
while(deci != 0)
{
digitvalue = deci % tobase;
ch = digitvalue + '0';
result = ch + result;
deci = deci / tobase;
}

if(result == "")
{
ch = deci + '0';
result = result + ch;
}
return result;

}
int main()
{
string num, result;
int frombase, tobase;

cout << "Enter from base (between 2 - 200): ";
cin >> frombase;

cout << "Enter to base (between 2 - 200): ";
cin >> tobase;

cout << "Enter a number in base " << frombase << ": ";
cin >> num;

result = convert(num, frombase, tobase);

cout << "The number " << num << " (base " << frombase << ") is "
<< result << " (base " << tobase << ")" << endl;

}


output
======

Enter from base (between 2 - 200): 10
Enter to base (between 2 - 200): 2
Enter a number in base 10: 12
The number 12 (base 10) is 1010 (base 2)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote