常規算法:
#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;
}