int hexCharToDec(char hexChar) { switch (hexChar) { case 'a': return 10; break; case 'b': return 11; break; case 'c': return 12; break; case 'd': return 13; break; case 'e': return 14; break; case 'f': return 15; break; default: return hexChar - 48; break; } }
int hexToDec(string hexString) { std::transform(hexString.begin(), hexString.end(), hexString.begin(), ::tolower); int power = 0, ret = 0; for (string::reverse_iterator rit = hexString.rbegin(); rit != hexString.rend(); ++rit) { ret += hexCharToDec(*rit) * pow(16, power); power++; } return ret; }
Answers & Comments
#include <string>
#include <math.h>
#include <algorithm>
using namespace std;
int hexCharToDec(char hexChar)
{
switch (hexChar) {
case 'a':
return 10;
break;
case 'b':
return 11;
break;
case 'c':
return 12;
break;
case 'd':
return 13;
break;
case 'e':
return 14;
break;
case 'f':
return 15;
break;
default:
return hexChar - 48;
break;
}
}
int hexToDec(string hexString)
{
std::transform(hexString.begin(), hexString.end(), hexString.begin(), ::tolower);
int power = 0, ret = 0;
for (string::reverse_iterator rit = hexString.rbegin(); rit != hexString.rend(); ++rit) {
ret += hexCharToDec(*rit) * pow(16, power);
power++;
}
return ret;
}
int main()
{
string s;
cout << "Строка: ";
cin >> s;
cout << endl << "Ответ: " << hexToDec(s) << endl;
return 0;
}