常规算法:
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
int change(string a, int n)
{
int sum = 0;
int x, tmp, b;//x是当前位数0~n-1
for (x = 0; n > 0; n--, x++)
{
//如果字符是数字
if ((a[x] >= '0') && (a[x] <= '9'))
{
//b为字符对应的10进制数值
b = a[x] - '0';
tmp = pow(16, n - 1);//当前位的16的次方
tmp = tmp * b;//当前值
sum = sum + tmp;
}
//如果字符是小写字母
else if ((a[x] >= 'a') && (a[x] <= 'f'))
{
b = a[x] - 'a' + 10;
tmp = pow(16, n-1);
tmp = tmp * b;
sum = sum + tmp;
}
//如果字符是小写字母
else if ((a[x] >= 'A') && (a[x] <= 'F'))
{
b = a[x] - 'A' + 10;
tmp = pow(16, n-1);
tmp = tmp * b;
sum = sum + tmp;
}
//否则为不正确的字符输入格式
else
{
cout << "The addr is meaningless, please re-enter!";
return 0;
}
}
return sum;
}
int main()
{
int n,sum;
string a;
cout << "please enter register addr as Hex:"<<endl;
cin >> a;
n = a.size();
sum=change(a, n);
cout << "The addr's decimal is " << sum << endl;
return 0;
}
C++11自带函数
int main()
{
int n,sum;
string a;
cout << "please enter register addr as Hex:"<<endl;
cin >> a;
n = std::stoi(a, nullptr, 16);
cout << "The addr's decimal is " << n << endl;
return 0;
}