Hex Dump

Here follows a basic C++ hex dumper function.  It is public domain so do whatever you want with it.
 

#include <ostream>
#include <string>

namespace neolib
{
	template<class Elem, class Traits>
	inline void hex_dump(const void* aData, std::size_t aLength, std::basic_ostream<Elem, Traits>& aStream, std::size_t aWidth = 16)
	{
		const char* const start = static_cast<const char*>(aData);
		const char* const end = start + aLength;
		const char* line = start;
		while (line != end)
		{
			aStream.width(4);
			aStream.fill('0');
			aStream << std::hex << line - start << " : ";
			std::size_t lineLength = std::min(aWidth, static_cast<std::size_t>(end - line));
			for (std::size_t pass = 1; pass <= 2; ++pass)
			{	
				for (const char* next = line; next != end && next != line + aWidth; ++next)
				{
					char ch = *next;
					switch(pass)
					{
					case 1:
						aStream << (ch < 32 ? '.' : ch);
						break;
					case 2:
						if (next != line)
							aStream << " ";
						aStream.width(2);
						aStream.fill('0');
						aStream << std::hex << std::uppercase << static_cast<int>(static_cast<unsigned char>(ch));
						break;
					}
				}
				if (pass == 1 && lineLength != aWidth)
					aStream << std::string(aWidth - lineLength, ' ');
				aStream << " ";
			}
			aStream << std::endl;
			line = line + lineLength;
		}
	}
}

Example usage:
 

#include <iostream>
#include <string>

#include <neolib/hexdump.hpp>

int main()
{
	std::string r;
	for (int i = 0; i != 100; ++i)
	{
		r += rand() % 256;
	}
	neolib::hex_dump(r.c_str(), r.size(), std::cout);
}

Example output:
 

0000 : )#...l..R.I..... 29 23 BE 84 E1 6C D6 AE 52 90 49 F1 F1 BB E9 EB
0010 : ...<..>.$^....G. B3 A6 DB 3C 87 0C 3E 99 24 5E 0D 1C 06 B7 47 DE
0020 : ..M.C.....Z}.8%. B3 12 4D C8 43 BB 8B A6 1F 03 5A 7D 09 38 25 1F
0030 : ].....E;.......2 5D D4 CB FC 96 F5 45 3B 13 0D 89 0A 1C DB AE 32
0040 :  .P.@x6..I2..}I. 20 9A 50 EE 40 78 36 FD 12 49 32 F6 9E 7D 49 DC
0050 : .O..D@f.k.0.2;." AD 4F 14 F2 44 40 66 D0 6B C4 30 B7 32 3B A1 22
0060 : ."..             F6 22 91 9D

You can e-mail comments to the author.

Back to project page