Linux操作使用

Unix / Linux: Create Binary File from Hex Dump

Objective: Create or convert a text hex dump input file to a binary file on Unix / Linux.

To convert a hex dump to a binary file, we will need to use the xxd utility. Let’s look at an example.

$ echo -ne "hello world 012\nhello world 012\n" | hexdump -ve '16/1 "%02x " "\n"'
68 65 6c 6c 6f 20 77 6f 72 6c 64 20 30 31 32 0a
68 65 6c 6c 6f 20 77 6f 72 6c 64 20 30 31 32 0a

The above is a hex dump of the string that we passed to the echo command. Now, let’s pipe that hex dump output to a file.

$ echo -ne "hello world 012\nhello world 012\n" | hexdump -ve '16/1 "%02x " "\n"' > input.hex
$ xxd -r -p input.hex output.bin

We have created a file called "output.bin", which is the binary output file based on the input hex dump file, "input.hex". To verify that the binary output is the same as our original input, we can run hexdump on it again.

$ cat output.bin | hexdump -ve '16/1 "%02x " "\n"'
68 65 6c 6c 6f 20 77 6f 72 6c 64 20 30 31 32 0a
68 65 6c 6c 6f 20 77 6f 72 6c 64 20 30 31 32 0a

As you can see, the hex dump contents are the same. If you would like xxd to read from stdin (standard input) instead of a input file, replace the input file parameter with ‘-‘ character. The example below shows xxd reading input from stdin.

$ echo -ne "hello world 012\nhello world 012\n" | hexdump -ve '16/1 "%02x " "\n"' | xxd -r -p - output.bin