Convert a hex dump back to its original binary form

user4515590 picture user4515590 · Oct 30, 2015 · Viewed 7.8k times · Source

I need do reverse Hex Dump, convert nvram memory block hex dump to the binary file (.bin). The memory block dump looks like this:

00010000    4293  D306  0123  195A  3360  18EB  66D0  60CB
00010010    E003  68C9  42B9  D1EE  1C0F  2201  4494  4663
00010020    B2DC  1C2B  335C  781B  42A3  D8C6  1C2B  33A0
00010030    1C34  601E  E039  4B21  681B  930A  7822  920B
00010040    8863  88A2  469C  23F8  021B  421A  D001  22A7
.... ....

Should I use just this xxd command, without additional options?

xxd -r block.txt block.bin

Answer

Diego Augusto Molina picture Diego Augusto Molina · Oct 30, 2015

You can try to. I did the following test:

$ echo "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed" | xxd
0000000: 4c6f 7265 6d20 6970 7375 6d20 646f 6c6f  Lorem ipsum dolo
0000010: 7220 7369 7420 616d 6574 2c20 636f 6e73  r sit amet, cons
0000020: 6563 7465 7475 7220 6164 6970 6973 6369  ectetur adipisci
0000030: 6e67 2065 6c69 742c 2073 6564 0a         ng elit, sed.

As you can see, it defers a bit from the input you have, so I made some modifications:

$ echo "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed" | xxd -u |
sed 's/^\(.\{48\}\).*$/\1/1; s/\(\S\s\)\(\S\)/\1 \2/g; s/:/  /;'
0000000    4C6F  7265  6D20  6970  7375  6D20  646F  6C6F
0000010    7220  7369  7420  616D  6574  2C20  636F  6E73
0000020    6563  7465  7475  7220  6164  6970  6973  6369
0000030    6E67  2065  6C69  742C  2073  6564  0A       

Which is pretty much similar to what you've got. Now I will try to revert that:

$ echo "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed" | xxd -u |
sed 's/^\(.\{48\}\).*$/\1/1; s/\(\S\s\)\(\S\)/\1 \2/g; s/:/  /;' | xxd -r
xxd: sorry, cannot seek backwards.

And that's awful. So, we would try to revert the changes in order to get a suitable input for xxd -r:

$ echo "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed" | xxd -u |
sed 's/^\(.\{48\}\).*$/\1/1; s/\(\S\s\)\(\S\)/\1 \2/g; s/:/  /;' |
sed 's/\s\+/ /g; s/^\(\S\+\)\s/\1: /'
0000000: 4C6F 7265 6D20 6970 7375 6D20 646F 6C6F
0000010: 7220 7369 7420 616D 6574 2C20 636F 6E73
0000020: 6563 7465 7475 7220 6164 6970 6973 6369
0000030: 6E67 2065 6C69 742C 2073 6564 0A 

And, at least for this example, it works:

$ echo "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed" | xxd -u |
sed 's/^\(.\{48\}\).*$/\1/1; s/\(\S\s\)\(\S\)/\1 \2/g; s/:/  /;' |
sed 's/\s\+/ /g; s/^\(\S\+\)\s/\1: /' | xxd -r
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed

So, to summarize, you can try the following:

sed 's/\s\+/ /g; s/^\(\S\+\)\s/\1: /' block.txt | xxd -r > block.bin