decimalValue + pow(16f,hex.size()-index-1) * hexCharToDec(hex[index]);
Does this work?
does this code look right for the binary to decimal conversion?
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int binToDec(const string &bin);
int binIntToDec(int binaryValues);
int main()
{
cout << "Enter a binary number: ";
string bin;
cin >> bin;
int decimal = -1;
decimal = binToDec(bin);
if (decimal != -1)
cout << "The decimal value for binary number " << bin << " is " << decimal << endl;
cin.get();
cin.get();
return 0;
}
int binToDec(const string &bin)
{
int decimalValue = 0;
for (int index = 0; index < bin.size(); index++)
{
try
{
int binaryValues = bin[index];
//Throw an exception if not a binary string
if (!(binaryValues == 0 || binaryValues == 1))
{
throw runtime_error("String is not a binary string");
}
else
decimalValue = decimalValue * 2 + binIntToDec(bin[index]);
}
catch (runtime_error e)
{
cout << e.what();
return -1;
}
}
return decimalValue;
}