In: Computer Science
c ++ program that converts from any base to a decimal number
C++ program : (Converts from any base to a decimal number)
#include <iostream>
using namespace std;
/*
To find decimal equivalent of a number N in any base we have the formula ,
let n be the length of number then, (Here ^ represents power symbol)
Decimal Equivalent = ((base)^0 )*N[n-1] + ((base)^1) * N[n-2] + ((base)^2) * N[n-3] + ....
*/
int main()
{
string num;
int base;
cout << "Please enter a number: ";
cin >> num;
cout << "Please enter the base of the number: ";
cin >> base;
int n = num.length(); // n stores length of number
int power = 1;
int result = 0, digit, flag = 1; // decimal value is stored in result
for(int i = n-1; i>=0; i--) // iterate through all digits in number
{
if(num[i]>='0' && num[i]<='9') // convert characters to integers
{
digit = (int)num[i] - '0';
}
else // convert characters to integers , Here 'A' = 10, 'B' = 11 ... 'Z' = 36
{
digit = (int)num[i] - 'A' + 10;
}
if(digit >=base) // if digit is greater than base then its invalid number for the given base
{
flag = 0;
cout << "You have entered a invalid number for the given base\n";
break;
}
result += digit*power; // calculate result
power = power*base; // multiply power with base
}
if(flag) // if flag is set to 1 then we get decimal equivalent for valid number for that base
{
cout<< "Decimal equivalent of "<<num<<" in base "<<base<<" is "<<result<<"\n";
}
return 0;
}
Screenshots and outputs :