Skip to content

Instantly share code, notes, and snippets.

@fa7ad
Created Mar 11, 2018
Embed
What would you like to do?
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
using namespace std;
typedef string::iterator strit;
const string charset("0123456789ABCDEF");
class Number {
string value;
int base;
int convToDec (string num, int base);
public:
Number () {}
Number (string v, int b) {
value = v;
base = b;
}
void setValue (string v);
void setBase (int b);
string getValue ();
int getBase();
string convertToBase(int inputBase);
};
int main (void) {
Number n1("12", 10), n2;
n2.setBase(2);
n2.setValue("1111");
cout
<< "\t\t" << "Value" << "\t\t" << "Base" << endl
<< "Input\t\t" << n1.getValue() << "\t\t" << n1.getBase() << endl
<< "Output\t\t" << n1.convertToBase(16) << "\t\t" << 16 << endl
<< "\t\t" << "---" << "\t\t" << "---" << endl
<< "Input\t\t" << n2.getValue() << "\t\t" << n2.getBase() << endl
<< "Output\t\t" << n2.convertToBase(8) << "\t\t" << 8 << endl;
return 0;
}
void Number::setValue (string v) {
value = v;
}
void Number::setBase (int b) {
base = b;
}
string Number::getValue () {
return value;
}
int Number::getBase () {
return base;
}
int Number::convToDec (string num, int base) {
int i = num.length(), dec = 0;
for(strit it = num.begin(); it != num.end(); it++){
int val = charset.find(*it);
dec += val * pow(base, --i);
}
return dec;
}
string Number::convertToBase (int inputBase) {
stringstream res;
int inTen = convToDec(this->value, this->base);
if (inputBase == 10){
res << inTen;
return res.str();
}
int temp = inTen;
while (temp > 0) {
int r = temp % inputBase;
res << charset[r];
temp /= inputBase;
}
string t(res.str());
return string(t.rbegin(), t.rend());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment