Skip to content

Instantly share code, notes, and snippets.

@tomalakgeretkal
Created June 20, 2019 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomalakgeretkal/594da2d34c51c3642a6f844333ae9e52 to your computer and use it in GitHub Desktop.
Save tomalakgeretkal/594da2d34c51c3642a6f844333ae9e52 to your computer and use it in GitHub Desktop.
hexdump of arbitrary data
#include <string>
#include <string_view>
#include <sstream>
#include <iomanip>
std::string hexdump(const char* buf, std::size_t len)
{
constexpr std::size_t cols = 32;
std::stringstream ss;
ss << "[loc: " << (const void*)buf << "; bytes: " << len
<< "; hash: " << std::hash<std::string_view>()(std::string_view((const char*)buf, len)) << "]\n";
ss << std::hex;
for (size_t i = 0; i < len; i += cols)
{
size_t j = i;
for (; j < len && j - i < cols; ++j)
ss << std::setw(2) << std::setfill('0') << +(unsigned char)buf[j] << ' ';
for (; j - i < cols; ++j)
ss << " ";
ss << "| ";
j = i;
for (; j < len && j - i < cols; ++j)
{
if (buf[j] >= 32 && buf[j] < 128)
ss << buf[j];
else
ss << ' ';
}
ss << '\n';
}
return ss.str();
}
@tomalakgeretkal
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment