I searched char*
to hex
string before but implementation I found adds some non-existent garbage at the end of hex
string. I receive pa
Code snippet above provides incorrect byte order in string, so I fixed it a bit.
char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C','D','E','F'};
std::string byte_2_str(char* bytes, int size) {
std::string str;
for (int i = 0; i < size; ++i) {
const char ch = bytes[i];
str.append(&hex[(ch & 0xF0) >> 4], 1);
str.append(&hex[ch & 0xF], 1);
}
return str;
}
Supposing data is a char*. Working example using std::hex:
for(int i=0; i<data_length; ++i)
std::cout << std::hex << (int)data[i];
Or if you want to keep it all in a string:
std::stringstream ss;
for(int i=0; i<data_length; ++i)
ss << std::hex << (int)data[i];
std::string mystr = ss.str();