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!
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();
                        Here is something:
char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
for( int i = data; i < data_length; ++i )
{
    char const byte = data[i];
    string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
    string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}
                        The simplest:
int main()
{
    const char* str = "hello";
    for (const char* p = str; *p; ++p)
    {
        printf("%02x", *p);
    }
    printf("\n");
    return 0;
}
                        I've found good example here Display-char-as-Hexadecimal-String-in-C++:
  std::vector<char> randomBytes(n);
  file.read(&randomBytes[0], n);
  // Displaying bytes: method 1
  // --------------------------
  for (auto& el : randomBytes)
    std::cout << std::setfill('0') << std::setw(2) << std::hex << (0xff & (unsigned int)el);
  std::cout << '\n';
  // Displaying bytes: method 2
  // --------------------------
  for (auto& el : randomBytes)
    printf("%02hhx", el);
  std::cout << '\n';
  return 0;
Method 1 as shown above is probably the more C++ way:
Cast to an unsigned int
Usestd::hexto represent the value as hexadecimal digits
Usestd::setwandstd::setfillfrom<iomanip>to format
Note that you need to mask the cast int against0xffto display the least significant byte:(0xff & (unsigned int)el).Otherwise, if the highest bit is set the cast will result in the three most significant bytes being set to
ff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With