Hexdump reverse command

I've written a short AWK script which reverses hexdump -C output back to the original data. Use like this:

reverse-hexdump.sh hex.txt > data

Handles '*' repeat markers and generating original data even if binary. hexdump -C and reverse-hexdump.sh make a data round-trip pair. It is available here:

  • GitHub reverse-hexdump repo
  • Direct to reverse-hexdump.sh

Restore file, given only the output of hexdump file

If you only have the output of hexdump file and want to restore the original file, first note that hexdump's default output depends on the endianness of the system you ran hexdump on!

If you have access to the system that created the dump, you can determinate its endianness using below command:

[[ "$(printf '\01\03' | hexdump)" == *0103* ]] && echo big || echo little

Reversing little-endian hexdump

This is the most common case. All x86/x64 systems are little-endian. If you don't know the endianness of the system that ran hexdump file, try this.

sed 's/ \(..\)\(..\)/ \2\1/g;$d' dump | xxd -r

The sed part converts hexdump's format into xxd's format, at least so far that xxd -r works.

Reversing big-endian hexdump

sed '$d' dump | xxd -r

Known Bugs (see comment section)

  • A trailing null byte is added if the original file was of odd length (e.g. 1, 3, 5, 7, ..., byte long).
  • Repeating sections of the original file are not restored correctly if they were hexdumped using a *.

You can check your dump for above problematic cases by running below command:

grep -qE '^\*|^[0-9a-f]*[13579bdf] *$' dump && echo bug || echo ok

Better alternative to create hexdumps in the first place

Besides the non-posix (and therefore not so portable) xxd there is od (octal dump) which should be available on all unix-like systems as it is specified by posix:

od -tx1 -An -v

Will print a hexadecimal dump, grouping digits as single bytes (-tx1), with no Address prefixes (-An, similar to xxd -p) and without abbreviating repeated sections as * (-v). You can reverse such a dump using xxd -r -p.


There is a similar tool called xxd. If you run xxd with just a file name it dumps the data in a fairly standard hex dump format:

# xxd bdata
0000000: 0001 0203 0405
......

Now if you pipe the output back to xxd with the -r option and redirect that to a new file, you can convert the hex dump back to binary:

# xxd bdata | xxd -r >bdata2
# cmp bdata bdata2
# xxd bdata2
0000000: 0001 0203 0405