问题:从键盘输入一个不超过8位的正的十六进制数字符串,将它转换为正的十进制数后输出。
注:十六进制数中的10~15分别用大写的英文字母A、B、C、D、E、F表示。
我的思路就是直接把16进制的数拆分为二进制的数,然后转换为十进制的数。
#include <iostream>
#include <string.h>
using namespace std;
int i;
string transform(string a)
{
string b="";
for(i=0;i<a.length();i++)
{
switch(a[i])
{
case '0':b+="0000";break;
case '1':b+="0001";break;
case '2':b+="0010";break;
case '3':b+="0011";break;
case '4':b+="0100";break;
case '5':b+="0101";break;
case '6':b+="0110";break;
case '7':b+="0111";break;
case '8':b+="1000";break;
case '9':b+="1001";break;
case 'A':b+="1010";break;
case 'B':b+="1011";break;
case 'C':b+="1100";break;
case 'D':b+="1101";break;
case 'E':b+="1110";break;
case 'F':b+="1111";break;
}
}
return b;
}
int main()
{
string s1,s2;
long long temp=0;
cin>>s1;
s2=transform(s1);
for(i=0;i<s2.length();i++)
{
temp<<=1;
temp+=(s2[i]-'0'); //减去ASCII码的值
}
cout<<temp;
return 0;
}
总结:
1.temp需要赋予初值,否则会出现乱码。
2.需要注意字符到整型转换,即减去‘0’的ASCII码。
3.知道了C++中string字符串的使用方法。