Linux – Tool to convert a file of HEX to ASCII character set

asciihexadecimallinux

Question:

  • Is there a known tool to convert a file consisting of 2 byte Hex into ascii?

Note: – Maintain file offset listing in bytes

Example:

File contents:

00000000  0054 0065 0073 0074 0020 0054 0065 0073
00000008  0074 0020 0054 0065 0073 0074 0020 0054
00000016  0065 0073 0074 0020 0054 0065 0073 0074
00000024  0020 0054 0065 0073 0074 0020 0054 0065
00000032  0073 0074 0020 0054 0065 0073 0074 0020
00000040  0054 0065 0073 0074 000a 0054 0065 0073
00000048  0074 0020 0054 0065 0073 0074 0020 0054
00000056  0065 0073 0074 0020 0054 0065 0073 0074
00000064  0020 0054 0065 0073 0074 0020 0054 0065

Expected output

00000016  0065 0073 0074 0020 0054 0065 0073 0074  |est Test Test Te|
00000032  0073 0074 0020 0054 0065 0073 0074 0020  |st Test Test.Tes|
00000048  0074 0020 0054 0065 0073 0074 0020 0054  |t Test Test Test|
00000064  0020 0054 0065 0073 0074 0020 0054 0065  | Test Test Test |

Best Answer

Your input file looks like it was produced using something like this:

hexdump -e '"%08_ad  "  8/1 "%04x "' -e '"" 0/0 "" "\n"' original_file

Unfortunately, xxd -r can't deal with decimal offsets.

Here is a short Gnu AWK program to give you the output you're looking for:

gawk '{printf "%s  |", $0; for (f=2; f<=9; f++) { c = strtonum("0x" $f); if (c >= 32 && c <= 126) printf "%c",c; else printf "."}; printf "|\n"}' input_file

If you're using an AWK other than gawk, you can use the strtonum() function here.

Here's another way to do the same thing as the gawk script above:

cut -c 11- input_file | sed 's/\<00//g' | xxd -r -p | hexdump -e '"%08_ad  "  8/1 "%04x " ""' -e '"  |" 8/1 "%_p" "|\n"'

If, instead, you want to convert your input file to text:

cut -c 11- input_file | xxd -r -p
Related Question