Strings are commonly encoded as hexadecimal (hex) strings for various purposes. Hence, it is also common to convert hex strings to its original strings such as an ASCII string. Hex to ASCII string conversion can be done programmatically in many languages. In command line, we can use
xxd to convert hex to ASCII string. This makes hex to ascii string conversion easy and handy, especially during debugging.
Table of Contents
Let’s first take a look at
xxd, its functions and command line options.
xxd is a tool to make a hexdump or do the reverse. That is,
xxd can create a hex dump of a given file or standard input, and also convert a hex dump back to its original binary form. For ASCII strings, the “binary form” is the plain string form.
For ASCII to Hex,
xxd generate the hex dump as follows with its default options.
$ echo "abcdefghijklmnopqrstuvwxyz" | xxd 00000000: 6162 6364 6566 6768 696a 6b6c 6d6e 6f70 abcdefghijklmnop 00000010: 7172 7374 7576 7778 797a 0a qrstuvwxyz.
Here, the hex string for “abcdefghijklmnopqrstuvwxyz” is “6162636465666768696a6b6c6d6e6f707172737475767778797a0a”.
Although by default
xxd uses its own 3-column format for the hex dump,
xxd supports several options for different functions and formats. Following are some options we will use for the purpose of hex to ASCII string conversion.
-p | -ps | -postscript | -plain
Output in postscript continuous hexdump style. Also known as plain hexdump style.
-r | -revert
Reverse operation: convert (or patch) hexdump into binary. If not writing to stdout, xxd writes into its output file without truncating it. Use the combination -r -p to read plain hexadecimal dumps without line number information and without a particular column layout. Additional Whitespace and line-breaks are allowed anywhere.
Use upper case hex letters. Default is lower case.
Convert hex to ASCII using xxd
Now let’s see how to convert the hex string to ASCII string with the above example for the given hex string “6162636465666768696a6b6c6d6e6f707172737475767778797a0a”.
Convert lower case hex to ASCII using xxd
We combine the options
-r together for
xxd and we can get the ASCII string.
$ echo "6162636465666768696a6b6c6d6e6f707172737475767778797a0a" | xxd -p -r abcdefghijklmnopqrstuvwxyz
Convert upper case hex to ASCII using xxd
If the hex string is in upper case, add the
$ echo "6162636465666768696A6B6C6D6E6F707172737475767778797A0A" | xxd -p -r abcdefghijklmnopqrstuvwxyz