练习2.1 十六进制转换为十进制
string MySystem::HexToBinary(string str)
{
//str应该是0x或者0X开头,所以长度应该大于2
if (str.size() < 2)
{
return "";
}
if ('0' != str[0] && 'x' != tolower(str[1]))
{
return "";
}
//保存结果
string Result("");
//保存匹配的结果
typedef pair<char, string> Match;
map<char, string> Map;
Map.insert(Match('0', "0000"));//0
Map.insert(Match('1', "0001"));//1
Map.insert(Match('2', "0010"));//2
Map.insert(Match('3', "0011"));//3
Map.insert(Match('4', "0100"));//4
Map.insert(Match('5', "0101"));//5
Map.insert(Match('6', "0110"));//6
Map.insert(Match('7', "0111"));//7
Map.insert(Match('8', "1000"));//8
Map.insert(Match('9', "1001"));//9
Map.insert(Match('a', "1010"));//10
Map.insert(Match('b', "1011"));//11
Map.insert(Match('c', "1100"));//12
Map.insert(Match('d', "1101"));//13
Map.insert(Match('e', "1110"));//14
Map.insert(Match('f', "1111"));//15
map<char, string>::iterator iter;
for (int i = 2; i < str.size();++i)
{
iter = Map.find(tolower(str[i]));
if (iter!=Map.end())
{
Result += iter->second;
}
}
return Result;
}
string MySystem::HexToBinary(string str)
{
//str应该是0x或者0X开头,所以长度应该大于2
if (str.size() < 2)
{
return "";
}
if ('0' != str[0] && 'x' != tolower(str[1]))
{
return "";
}
//保存结果
string Result("");
//保存匹配的结果
typedef pair<char, string> Match;
map<char, string> Map;
Map.insert(Match('0', "0000"));//0
Map.insert(Match('1', "0001"));//1
Map.insert(Match('2', "0010"));//2
Map.insert(Match('3', "0011"));//3
Map.insert(Match('4', "0100"));//4
Map.insert(Match('5', "0101"));//5
Map.insert(Match('6', "0110"));//6
Map.insert(Match('7', "0111"));//7
Map.insert(Match('8', "1000"));//8
Map.insert(Match('9', "1001"));//9
Map.insert(Match('a', "1010"));//10
Map.insert(Match('b', "1011"));//11
Map.insert(Match('c', "1100"));//12
Map.insert(Match('d', "1101"));//13
Map.insert(Match('e', "1110"));//14
Map.insert(Match('f', "1111"));//15
map<char, string>::iterator iter;
for (int i = 2; i < str.size();++i)
{
iter = Map.find(tolower(str[i]));
if (iter!=Map.end())
{
Result += iter->second;
}
}
return Result;
}