2025-08-20 Clever hexdump in C
Programming in C get's better and better, not with time but with each project.
It's not the years, honey. It's the mileage.
- Indy
Recently inspired by Ivan's video [1] I wrote my own small hexdump function in just few lines of C. here it is:
/* Dump N bytes from BUF in hexdump format to stdout. */
void
hexdump(char *buf, int n)
{
int i, j;
for (i=0; i
Example output:
00000000 23 69 6E 63 6C 75 64 65 20 3C 73 74 64 6C 69 62 #include .#include .#include
00000030 20 22 75 74 66 2E 68 22 0A 23 69 6E 63 6C 75 64 "utf.h".#includ
There is nothing particularly interesting about this implementation except for single condition in last printf for loop, the one that detect if we should print dot or ASCII character. Here is the cleaner version of it:
printf("%c", c < ' ' ? '.' : c); // where 'c' is currently printed byte
What's strange about it is that we supposed to check byte value to see if it is a printable ASCII character by checking upper and lower boundary. Sounds like 2 conditions. So why single check of `c` being smaller than space is enough? Look at the bits of first and last printable ASCII characters.
0x20 00100000 32 First printable ASCII character
0x7F 01111111 127 Last printable ASCII character
0x80 10000000 -128 First non printable value
And now remember that type `char` is a signed number. As soon as you increment beyond last printable ASCII character the value becomes negative falling into `c < ' '` condition.
The Dark Side of the Code is a pathway to many abilities some consider to be unnatural.
- Probably some C programmer
I CHALLENGE YOU 🫵 TO WRITE SHORTER VERSION!
I found this basic hexdum function very helpful and easier to use than external programs. The ability to write that on spot without second though is a nice skill to have. I was looking for even simpler ways of achieving the same or similar output. It might be possible to do some tricks with mod operator to avoid nested loops. I decided to stick with this very straightforward code but if you find a shorter / better / simpler way then I would love to see it.
EOF