Char array to hex string C++

Roman picture Roman · May 23, 2012 · Viewed 114.9k times · Source

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!

Answer

Jorge González Lorenzo picture Jorge González Lorenzo · Mar 20, 2014

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