Char array to hex string C++

buffer, byte, c++, hex

Solution

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();

Problem

I searched `char*` to `hex` string before but implementation I found adds some non-existent garbage at the end of `hex` string. I receive packets from socket, and I need to convert them to `hex` strings for log (null-terminated buffer). Can somebody advise me a good implementation for `C++`? Thanks!

Original source

Related problems