C++中hex字符串与byte数据的互相转换

#include <iostream>
#include <cstring>
using namespace std;
/**
* 将二进制数据转换为可见的hex字符串
* @param bytes 原始数据
* @param bytesLength 要转换的字节长度
* @return hex字符串
* */
string bytesToHexString(char* bytes,int bytesLength)
{
string str(“”);
string str2(“0123456789abcdef”);
for (int i=0; i<bytesLength; i++)
{
int b;
b = 0x0f & (bytes[i] >> 4);
char s1 = str2.at(b);
str.append(1, str2.at(b));
b = 0x0f & bytes[i];
str.append(1, str2.at(b));
char s2 = str2.at(b);
}
return str;
}
int hexCharToInt(char c)
{
if (c >= ‘0’ && c <= ‘9’) return (c – ‘0’);
if (c >= ‘A’ && c <= ‘F’) return (c – ‘A’ + 10);
if (c >= ‘a’ && c <= ‘f’) return (c – ‘a’ + 10);
return 0;
}
/**
* hex字符串转换为char×
* @param s 要转换的hex字符串
* @return 二进制数据,以char*形式返回
* */
char* hexStringToBytes(string s)
{
int sz = s.length();
char *ret = new char[sz/2];
for (int i=0; i<sz; i+=2)
{
ret[i/2] = (char) ((hexCharToInt(s.at(i)) << 4) | hexCharToInt(s.at(i+1)));
}
return ret;
}
/**
* 测试代码
*/
int main()
{
cout << “Hello, World!” << endl;
char data[3] = {0,1,2};
char* bytes = “0123456”;
string string1 = bytesToHexString(bytes,7);
cout << “转换的hex字符串是:” << string1 << endl;
char* res = hexStringToBytes(string1);
cout << “hex字符串转换成原数据是:” << res << endl;
int resLength = strlen(res);
cout << “char*的长度是:” << resLength << endl;
return 0;
}

发表评论