string MySystem::BinaryToHex(string str)
{
if (str.empty())
{
return "";
}
int Complement = 0;//需要补充的位数 ---二进制数据不是4的倍数的话,需要在左边补0
int Length = str.size() % 4;
if (Length)
{
Complement = Length;
}
string Temp("");//保存已经添加过0的二进制数据
for (int i = 0; i < 4-Length&&0!=Length;++i)
{
Temp += '0';
}
Temp += str;
//保存匹配的结果
typedef pair<string, char> Match;
map<string, char> Map;
Map.insert(Match("0000",'0'));//0
Map.insert(Match("0001", '1'));//1
Map.insert(Match("0010", '2'));//2
Map.insert(Match("0011", '3'));//3
Map.insert(Match("0100", '4'));//4
Map.insert(Match("0101", '5'));//5
Map.insert(Match("0110", '6'));//6
Map.insert(Match("0111", '7'));//7
Map.insert(Match("1000", '8'));//8
Map.insert(Match("1001", '9'));//9
Map.insert(Match("1010", 'a'));//10
Map.insert(Match("1011", 'b'));//11
Map.insert(Match("1100", 'c'));//12
Map.insert(Match("1101", 'd'));//13
Map.insert(Match("1110", 'e'));//14
Map.insert(Match("1111", 'f'));//15
string Result("0X");
map<string, char>::iterator iter;
for (int i = 0; i < Temp.size();i+=4)
{
iter=Map.find(Temp.substr(i, 4));
if (iter!=Map.end())
{
Result += iter->second;
}
}
return Result;
}
{
if (str.empty())
{
return "";
}
int Complement = 0;//需要补充的位数 ---二进制数据不是4的倍数的话,需要在左边补0
int Length = str.size() % 4;
if (Length)
{
Complement = Length;
}
string Temp("");//保存已经添加过0的二进制数据
for (int i = 0; i < 4-Length&&0!=Length;++i)
{
Temp += '0';
}
Temp += str;
//保存匹配的结果
typedef pair<string, char> Match;
map<string, char> Map;
Map.insert(Match("0000",'0'));//0
Map.insert(Match("0001", '1'));//1
Map.insert(Match("0010", '2'));//2
Map.insert(Match("0011", '3'));//3
Map.insert(Match("0100", '4'));//4
Map.insert(Match("0101", '5'));//5
Map.insert(Match("0110", '6'));//6
Map.insert(Match("0111", '7'));//7
Map.insert(Match("1000", '8'));//8
Map.insert(Match("1001", '9'));//9
Map.insert(Match("1010", 'a'));//10
Map.insert(Match("1011", 'b'));//11
Map.insert(Match("1100", 'c'));//12
Map.insert(Match("1101", 'd'));//13
Map.insert(Match("1110", 'e'));//14
Map.insert(Match("1111", 'f'));//15
string Result("0X");
map<string, char>::iterator iter;
for (int i = 0; i < Temp.size();i+=4)
{
iter=Map.find(Temp.substr(i, 4));
if (iter!=Map.end())
{
Result += iter->second;
}
}
return Result;
}