void hexstring_from_data(const void *data, size_t len, char *output) {
const unsigned char *buf = (const unsigned char *)data;
size_t i, j;
for (i = j = 0; i < len; ++i) {
char c;
c = (buf[i] >> 4) & 0xf;
c = (c > 9) ? c + 'a' - 10 : c + '0';
output[j++] = c;
c = (buf[i] & 0xf);
c = (c > 9) ? c + 'a' - 10 : c + '0';
output[j++] = c;
}
}
std::string hexstring_from_data(const void *data, size_t len) {
if (len == 0) {
return std::string();
}
std::string result;
result.resize(len * 2);
hexstring_from_data(data, len, &result[0]);
return result;
}
//字符串转十六进制字符流 字符串
std::string hexstring_from_data(const std::string &data) {
return hexstring_from_data(data.c_str(), data.size());
}
void data_from_hexstring(const char *hexstring, size_t length, void *output) {
unsigned char *buf = (unsigned char *)output;
unsigned char byte;
if (length % 2 != 0) {
throw std::invalid_argument("data_from_hexstring length % 2 != 0");
}
for (size_t i = 0; i < length; ++i) {
switch (hexstring[i]) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
byte = (hexstring[i] - 'a' + 10) << 4;
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
byte = (hexstring[i] - 'A' + 10) << 4;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
byte = (hexstring[i] - '0') << 4;
break;
default:
throw std::invalid_argument("data_from_hexstring invalid hexstring");
}
++i;
switch (hexstring[i]) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
byte |= hexstring[i] - 'a' + 10;
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
byte |= hexstring[i] - 'A' + 10;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
byte |= hexstring[i] - '0';
break;
default:
throw std::invalid_argument("data_from_hexstring invalid hexstring");
}
*buf++ = byte;
}
}
std::string data_from_hexstring(const char *hexstring, size_t length) {
if (length % 2 != 0) {
throw std::invalid_argument("data_from_hexstring length % 2 != 0");
}
if (length == 0) {
return std::string();
}
std::string result;
result.resize(length / 2);
data_from_hexstring(hexstring, length, &result[0]);
return result;
}
//十六进制字符流转字符串
std::string data_from_hexstring(const std::string &hexstring) {
return data_from_hexstring(hexstring.c_str(), hexstring.size());
}
int main()
{
std::string str = "2e7c8080";
char str2[21] = {0};
str2[0] = 0x2E;
str2[1] = 0x7C;
str2[2] = 0x80;
str2[3] = 0x80;
std::string str22 = str2;
std::cout << "str: " << str << std::endl;
std::cout << "str22: " << str22 << std::endl;
std::cout << "data_from_hexstring: " << data_from_hexstring(str) << std::endl;
if (data_from_hexstring(str) == str22)
std::cout << "厉害厉害" << std::endl; 144
std::string comp = hexstring_from_data(str22);
std::cout << " hexstring_from_data: " << comp << std::endl;
if (str == comp)
std::cout << "牛啊牛啊" << std::endl;
return 0;
}