C++二进制字符串转十六进制字符串 十六进制字符串转二进制字符串

==============================================

    二进制转十六进制

==============================================

//__二进制转十六进制
std::string BinToHex(const std::string &strBin, bool bIsUpper/* = false*/)
{
std::string strHex;
strHex.resize(strBin.size() * );
for (size_t i = ; i < strBin.size(); i++)
{
uint8_t cTemp = strBin[i];
for (size_t j = ; j < ; j++)
{
uint8_t cCur = (cTemp & 0x0f);
if (cCur < )
{
cCur += '';
}
else
{
cCur += ((bIsUpper ? 'A' : 'a') - );
}
strHex[ * i + - j] = cCur;
cTemp >>= ;
}
} return strHex;
}

==============================================

    十六进制转二进制

==============================================

//十六进制转二进制
std::string HexToBin(const std::string &strHex)
{
if (strHex.size() % != )
{
return "";
} std::string strBin;
strBin.resize(strHex.size() / );
for (size_t i = ; i < strBin.size(); i++)
{
uint8_t cTemp = ;
for (size_t j = ; j < ; j++)
{
char cCur = strHex[ * i + j];
if (cCur >= '' && cCur <= '')
{
cTemp = (cTemp << ) + (cCur - '');
}
else if (cCur >= 'a' && cCur <= 'f')
{
cTemp = (cTemp << ) + (cCur - 'a' + );
}
else if (cCur >= 'A' && cCur <= 'F')
{
cTemp = (cTemp << ) + (cCur - 'A' + );
}
else
{
return "";
}
}
strBin[i] = cTemp;
} return strBin;
}

附1:C++二进制字符串转Base64字符串 Base64字符串转二进制字符串

上一篇:delphi如何把一个整数转化为4个十六进制字节


下一篇:字节(byte)、二进制、字节流、字符流相关概念分析