We often need to display the exact bytes stored within a region of memory, or we might be interested in the byte representation of a variable. Typically we want such things during debugging, or trying to understand binary based protocols.
Bytes are best displayed in hexadecimal notation (hex). So we require a function that takes a memory region (described by a pointer and size) and builds a string of the hex values for all bytes within the region.
The C++ function below does this. It is called hexdump because it is similar in spirit to the UNIX utility of the same name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> #include <iomanip> /** * Represent a memory region in hex. * Darren Smith, www.xxdev.com */ void hexdump(const unsigned char * p, size_t size, std::ostream& os, const char* prefix = NULL, bool brackets = false) { std::ios_base::fmtflags flags = os.flags(); // save state if (brackets) os << "["; // set up our stream for hex output os << std::setfill('0'); os << std::hex; os << std::uppercase; os << std::right; for (size_t i = 0; i < size; ++i) { if (prefix) os << prefix; os << std::setw(2) << static_cast<int>(p[i]) ; } os.flags(flags); // reset stream state if (brackets) os << "]"; } |
Note that it builds the hex string by inserting the hex values onto an output stream. For instant debugging we can use the C++ stream object cout to write the hex to stdout:
1 2 3 4 5 6 7 8 9 10 11 | int main(int argc, const char* argv[]) { if (argc > 1) { const char* buf = argv[1]; size_t bufSize = strlen(argv[1]); hexdump((const unsigned char*) buf, bufSize, std::cout, " "); std::cout << "n"; } } |