Skip to content

Instantly share code, notes, and snippets.

@smx-smx
Last active April 7, 2020 15:47
Show Gist options
  • Save smx-smx/00e04b96b63b6dcf524cae112c35627d to your computer and use it in GitHub Desktop.
Save smx-smx/00e04b96b63b6dcf524cae112c35627d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <sstream>
#include <string>
#include <cstdint>
#include <cctype>
static int round_up_div(int val, int div){
return (val + div - 1) / div;
}
#define HEXDUMP_ROW_PRESIZE 0x3D
#define HEXDUMP_ROW_POSTSIZE 0x11
#define HEXDUMP_ROW_SIZE 0x60
static void hexdump(std::ostream& out, void *pData, size_t length){
uint8_t *bytes = (uint8_t *)pData;
if(bytes == NULL || length == 0){
return;
}
size_t max = round_up_div(length, HEXDUMP_ROW_SIZE) * HEXDUMP_ROW_SIZE;
char buf[max];
std::stringstream ss;
ss.rdbuf()->pubsetbuf(buf, sizeof(buf));
size_t i = 0, j = 0, octets = 0;
while (i < length) {
// print address every 16 bytes
int offset = i & 15;
if (offset == 0) {
ss << ssprintf("%08X ", i);
}
// print byte
ss << ssprintf("%02X ", bytes[i++]);
// octets spacing
if (i > 0 && (i & 7) == 0) {
if (octets++ < 1){
ss << ' ';
}
}
if (octets == 2 || i == length) {
// fill blanks
off_t row_offs = ss.tellp() % HEXDUMP_ROW_SIZE;
if(row_offs > 0){
size_t needed = HEXDUMP_ROW_SIZE - HEXDUMP_ROW_POSTSIZE - row_offs;
ss << std::string(needed, ' ');
}
// go back to saved pos, and print the bytes content
for (size_t k = j; k < i; k++) {
if (!isprint((char)bytes[k])){
ss << '.';
} else {
ss << (char)(bytes[k]);
}
}
ss << '\n';
j = i;
octets = 0;
}
}
out << ss.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment