二进制转换为十六进制

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值