Created
January 5, 2013 13:20
-
-
Save neilxp/4461562 to your computer and use it in GitHub Desktop.
Dump hex of a buffer, that the format is (almost) identical to the output of `xxd` in Linux, so the dumped text could be parsed by `xxd -r`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef __DUMP_HEX_HEADER__ | |
#define __DUMP_HEX_HEADER__ | |
#define DH_NUM_BYTES_PER_LINE 16 | |
#define DH_HEX_POS 46 | |
#define DH_HEX_OFFSET 6 | |
#define DH_HEX_COLUMN_SIZE 8 | |
#define DH_SEPERATOR ' ' | |
#define DH_UNPRINTABLE '.' | |
#include <iomanip> | |
#include <assert.h> | |
#include <sstream> | |
// | |
// Compatile to `xxd -r` in Linux | |
// Output example: | |
// | |
// Dump hex value, size 82 | |
// 000000: 6861 6F72 6568 7572 616F 756C 6123 1199 haorehuraoula#.. | |
// 000010: E2BB BE75 6C72 6162 6575 6C72 6861 6C72 ...ulrabeulrhalr | |
// 000020: 6575 6368 616C 7265 7568 6C72 6168 6575 euchalreuhlraheu | |
// 000030: 6C72 6168 656C 7568 616C 6F65 7562 6172 lraheluhaloeubar | |
// 000040: 6378 6261 6C72 656F 626B 726C 6361 6F6B cxbalreobkrlcaok | |
// 000050: 3132 12 | |
static std::string dumpToHexString(const unsigned char* ptr, size_t len) | |
{ | |
if (ptr == NULL || len == 0) | |
{ | |
return "NULL"; | |
} | |
std::ostringstream overallOss, oss2; | |
overallOss << "Dump hex value, size " << len << std::endl; | |
overallOss << std::hex << std::uppercase << std::setw(6) << std::setfill('0') << int(0) << ": "; | |
size_t offset = 0, pos = 0; | |
for (size_t idx = 0; idx < len; idx++) | |
{ | |
offset = idx % DH_NUM_BYTES_PER_LINE; | |
if (offset == 0) pos = DH_HEX_OFFSET; | |
const unsigned char& byte = ptr[idx]; | |
overallOss << std::setw(2) << std::setfill('0') << (unsigned) byte; | |
pos += 2; | |
std::isprint(byte) != 0 ? oss2 << byte : oss2 << DH_UNPRINTABLE; | |
if (idx + 1 == len || offset + 1 == DH_NUM_BYTES_PER_LINE) | |
{ | |
overallOss << std::setw(DH_HEX_POS - pos + 2 ) | |
<< std::setfill(DH_SEPERATOR) << " " << oss2.str(); | |
oss2.str(""); | |
if (idx + 1 != len){ | |
overallOss << "\n"; | |
overallOss << std::hex << std::uppercase << std::setw(6) << std::setfill('0') << idx + 1 << ": "; | |
} | |
} | |
else if (offset + 1 == DH_HEX_COLUMN_SIZE) | |
{ | |
overallOss << std::setw(1) << std::setfill(DH_SEPERATOR) << ""; | |
pos += 1; | |
} | |
else if (offset % 2 == 1) | |
{ | |
overallOss << std::setw(1) << std::setfill(DH_SEPERATOR) << ""; | |
pos += 1; | |
} | |
} | |
return overallOss.str(); | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment