Implementing Base Conversion in C++
Convreting numbers between different numeral systems is a common task in programming. This involves three primary scenarios: converting from an arbitrary base to decimal, from decimal to another base, and directly between two non-decimal bases.
Converting from Base-X to Decimal
Each digit in a number represents a coefficient multiplied by the base raised to the power of its position (starting from 0 at the least significant digit). For example:
- Binary
1011equals $1 \cdot 2^3 + 0 \cdot 2^2 + 1 \cdot 2^1 + 1 \cdot 2^0 = 11$ in decimal. - Hexadecimal
2Cequals $2 \cdot 16^1 + 12 \cdot 16^0 = 44$ in decimal.
The following function implements this logic:
#include <iostream>
#include <string>
using namespace std;
int baseToDecimal(const string& num, int base) {
int result = 0;
int power = 1;
for (int i = num.size() - 1; i >= 0; --i) {
char c = num[i];
int digit = (c >= '0' && c <= '9') ? c - '0' : c - 'A' + 10;
result += digit * power;
power *= base;
}
return result;
}
Converting from Decimal to Base-X
This uses repeated division by the target base, collecting remainders. Digits greater than 9 are represented using uppercase letters (A–Z). A lookup string simplifies digit-to-character mapping:
#include <iostream>
#include <string>
using namespace std;
const string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string decimalToBase(int value, int base) {
if (value == 0) return "0";
string reversed = "";
while (value > 0) {
reversed += DIGITS[value % base];
value /= base;
}
string result = "";
for (int i = reversed.size() - 1; i >= 0; --i) {
result += reversed[i];
}
return result;
}
Converting from Base-X to Base-K
This combines the two previous steps: first convert the input from base-X to decimal, then from decimal to base-K.
#include <iostream>
#include <string>
using namespace std;
const string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int baseToDecimal(const string& num, int base) {
int result = 0;
int power = 1;
for (int i = num.size() - 1; i >= 0; --i) {
char c = num[i];
int digit = (c >= '0' && c <= '9') ? c - '0' : c - 'A' + 10;
result += digit * power;
power *= base;
}
return result;
}
string decimalToBase(int value, int base) {
if (value == 0) return "0";
string reversed = "";
while (value > 0) {
reversed += DIGITS[value % base];
value /= base;
}
string result = "";
for (int i = reversed.size() - 1; i >= 0; --i) {
result += reversed[i];
}
return result;
}
int main() {
string input;
int sourceBase, targetBase;
cin >> input >> sourceBase >> targetBase;
int decimalValue = baseToDecimal(input, sourceBase);
cout << decimalToBase(decimalValue, targetBase) << endl;
return 0;
}