Skip to content

Instantly share code, notes, and snippets.

@stevemk14ebr
Forked from shreyasbharath/hexdump.cpp
Last active April 12, 2020 20:04
Show Gist options
  • Save stevemk14ebr/42347a04aeadae0818ff0ad6d8ab74f6 to your computer and use it in GitHub Desktop.
Save stevemk14ebr/42347a04aeadae0818ff0ad6d8ab74f6 to your computer and use it in GitHub Desktop.
Hexdump - C++ version of XXD style hexdump (based on this StackOverflow answer https://stackoverflow.com/a/7776146/801008)
#include <iomanip>
#include <iostream>
#include <vector>
#include <termcolor.hpp>
void hexDump(const std::vector<uint8_t>& bytes, std::ostream& stream)
{
char buff[17];
size_t i = 0;
stream << std::hex;
for (i = 0; i < bytes.size(); i++)
{
if ((i % 16) == 0)
{
if (i != 0)
{
stream << " " << buff << std::endl;
}
// Output the offset.
stream << termcolor::blue;
stream << " " << std::setw(4) << std::setfill('0') << static_cast<unsigned int>(i);
stream << termcolor::reset;
}
stream << termcolor::green;
stream << " " << std::setw(2) << std::setfill('0') << static_cast<unsigned int>(bytes[i]);
stream << termcolor::reset;
if ((bytes[i] < 0x20) || (bytes[i] > 0x7e))
{
buff[i % 16] = '.';
} else {
buff[i % 16] = bytes[i];
}
buff[(i % 16) + 1] = '\0';
}
stream << std::dec;
while ((i++ % 16) != 0)
{
stream << " ";
}
stream << " " << buff << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment