HexDump Function
When programming at a low level, it’s often handy to be able to dump data to the console as raw hex values. Over the years I’ve written a handful of nearly identical routines to do this, but I’ve finally collected them into one function to rule them all. This function will dump a buffer to screen, 16 bytes per line, in both hex and ASCII format.
48 65 6c 6c 6f 20 61 6e 64 20 77 65 6c 63 6f 6d Hello.and.welcom
65 20 74 6f 20 68 74 74 70 3a 2f 2f 77 77 77 2e e.to.http://www.
77 61 79 6e 65 61 6e 64 6c 61 79 6e 65 2e 63 6f wayneandlayne.co
6d 21 00 m!.
Here is the function, HexDump, as well as a main function to demonstrate the usage:
void HexDump(char *buffer, int bytes)
{
int col = 0;
int i = 0;
char buff[18];
while (bytes--)
{
printf("%02x ", (unsigned char)*buffer); // print byte value
if (isgraph(*buffer))
sprintf(buff+col, "%c", (unsigned char)*buffer);
else
sprintf(buff+col, ".");
if (col == 15 || bytes == 0)
{
if (bytes == 0)
{
// end of buffer, figure out how many we are short.
for (int i = 0; i < 15-col; i++)
printf(" ");
}
printf(" %s\n", buff);
col = 0;
}
else col++;
buffer++;
}
}
int main(int argc, char* argv[])
{
char buf[] = "Hello and welcome to http://www.wayneandlayne.com!";
HexDump(buf, sizeof(buf));
return 0;
}