How to convert text file to binary using linux commands

I have the hexadecimal code of a binary file in text (string) format. How to convert it to binary using linux commands like cat and echo?

I know the command, the following command with creating the binary test.bin. But what if this hex code is in another .txt file? How do I β€œroll up” the contents of an β€œecho” text file and generate a binary file?

# echo -e "\x00\x001" > test.bin

+8
command-line linux unix shell
source share
3 answers

use xxd -r . it returns hexdump in its binary representation.

source and source

Change The -p also very useful. It accepts "simple" hexadecimal values, but ignores spaces and line changes.

So, if you have a simple text dump, for example:

 echo "0000 4865 6c6c 6f20 776f 726c 6421 0000" > text_dump 

You can convert it to binary with:

 xxd -r -p text_dump > binary_dump 

And then get useful output with something like:

 xxd binary_dump 
+15
source share

Besides xxd , you should also look at the od / hexdump packages / commands. All of them are similar, but each of them provides several different options that will allow you to adapt the output to your needs. For example, hexdump -C is a traditional hexdump with associated ASCII translation along the side.

0
source share

If you have long text or text in a file, you can also use the binmake tool, which allows you to describe some binary data in text format and generate a binary file (or output to stdout). This allows you to change the endianess and number formats and accept comments.

The default format is hexadecimal, but not limited to this.

First get and compile binmake :

 $ git clone https://github.com/dadadel/binmake $ cd binmake $ make 

You can use it with stdin and stdout :

 $ echo '32 decimal 32 61 %x20 %x61' | ./binmake | hexdump -C 00000000 32 20 3d 20 61 |2 = a| 00000005 

Or use files. So create your text file file.txt :

 # an exemple of file description of binary data to generate # set endianess to big-endian big-endian # default number is hexadecimal 00112233 # man can explicit a number type: %b means binary number %b0100110111100000 # change endianess to little-endian little-endian # if no explicit, use default 44556677 # bytes are not concerned by endianess 88 99 aa bb # change default to decimal decimal # following number is now decimal 0123 # strings are delimited by " or ' "this is some raw string" # explicit hexa number starts with %x %xff 

Create your binary file.bin file:

 $ ./binmake file.txt file.bin $ hexdump file.bin -C 00000000 00 11 22 33 4d e0 77 66 55 44 88 99 aa bb 7b 74 |.."3M.wfUD....{t| 00000010 68 69 73 20 69 73 20 73 6f 6d 65 20 72 61 77 20 |his is some raw | 00000020 73 74 72 69 6e 67 ff |string.| 00000027 
0
source share

All Articles