I wrote this function to convert an array of bytes to a C/C++ string representation using hexadecimal escape codes (\xhh
). Any suggestions are welcome:
std::string toEscapedHexaString(const std::uint8_t * data, const int dataSizeBytes,
const int maxCols = 80, const int padding = 0)
{
assert(data != nullptr);
assert((maxCols % 4) == 0);
assert((padding % 2) == 0);
int column = 0;
char hexaStr[64] = {'\0'};
std::string result = "\"";
for (int i = 0; i < dataSizeBytes; ++i, ++data)
{
std::snprintf(hexaStr, sizeof(hexaStr), "\\x%02X", static_cast<unsigned>(*data));
result += hexaStr;
column += 4;
if (column >= maxCols)
{
if (i != (dataSizeBytes - 1)) // If not the last iteration
{
result += "\"\n\"";
}
column = 0;
}
}
// Add zero padding at the end to ensure the data size
// is evenly divisible by the given padding value.
if (padding > 0)
{
for (int i = dataSizeBytes; (i % padding) != 0; ++i)
{
result += "\\x00";
column += 4;
if (column >= maxCols)
{
if ((i + 1) % padding) // If not the last iteration
{
result += "\"\n\"";
}
column = 0;
}
}
}
result += "\"";
return result;
}
You can control the number of columns in the output, so for example, converting Hello World!\0
with 20 columns max (not counting the quotes):
const unsigned char str[] = "Hello World!";
auto result = toEscapedHexaString(str, sizeof(str), 20);
/* result =
"\x48\x65\x6C\x6C\x6F"
"\x20\x57\x6F\x72\x6C"
"\x64\x21\x00"
*/