C语言实现字节流与十六进制字符串的相互转换
//字节流转换为十六进制字符串
void ByteToHexStr(const unsigned char* source, char* dest, int sourceLen)
{
short i;
unsigned char highByte, lowByte;
for (i = 0; i < sourceLen; i++)
{
highByte = source[i] >> 4;
lowByte = source[i] & 0x0f;
highByte += 0x30;
if (highByte > 0x39)
dest[i * 2] = highByte + 0x07;
else
dest[i * 2] = highByte;
lowByte += 0x30;
if (lowByte > 0x39)
dest[i * 2 + 1] = lowByte + 0x07;
else
dest[i * 2 + 1] = lowByte;
}
return;
}
//字节流转换为十六进制字符串的另一种实现方式
void Hex2Str(const char *sSrc, char *sDest, int nSrcLen)
{
int i;
char szTmp[3];
for (i = 0; i < nSrcLen; i++)
{
sprintf(szTmp, "%02X", (unsigned char)sSrc[i]);
memcpy(&sDest[i * 2], szTmp, 2);
}
return;
}
//string实现方法字节流转十六进制字符串
std::string ToHexString(const UCHAR* buf, int len, std::string tok/* = " "*/)
{
std::string output;
char temp[8];
for (int i = 0; i < len; ++i)
{
sprintf(temp, "%.2x", (UCHAR)buf[i]);
output.append(temp);
if (i < len -1)
{
output.append(tok);
}
}
return output;
}//十六进制字符串转换为字节流
void HexStrToByte(const char* source, unsigned char* dest, int sourceLen)
{
short i;
unsigned char highByte, lowByte;
for (i = 0; i < sourceLen; i += 2)
{
highByte = toupper(source[i]);
lowByte = toupper(source[i + 1]);
if (highByte > 0x39)
highByte -= 0x37;
else
highByte -= 0x30;
if (lowByte > 0x39)
lowByte -= 0x37;
else
lowByte -= 0x30;
dest[i / 2] = (highByte << 4) | lowByte;
}
return;
}声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: curl获得cookie数据
- 下一篇:没有了
