Going from hex to binary in Linux

If you find yourself with a block of \x encoded hex that you need converted back to it’s binary equivalent – in my particular case, an image encoded as a hex block back to it’s native JPEG file, you can use this short code snippit:

cat <input file> | sed -e ‘s/\\x//g’ -e ‘s/”//g’ -e ‘s/^[ \t]*//’ | xxd -p -r – <output file>

Adjust the sed arguments as needed to produce the trimming that you need to feed into xxd - when you pass -p to xxd you instruct it to take input as hexadecimal plaintext, and -r tells xxd to go from the hexadecimal string back it’s binary equivalent.

In this case, I used this to extract the images from the icons.c file for Minidlna.

Thanks to this LinuxJournal article for how to do a reverse hex dump.

Leave a Reply