How to convert a text file to binary file using linux commands

旧时模样 提交于 2020-01-22 09:29:09

问题


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

I know command following command with create a binary test.bin. But what if this hexcode is in another .txt file ? How do I "cat" the content of text file to "echo" and generate a binary file ?

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


回答1:


use xxd -r. it reverts a hexdump to its binary representation.

source and source

Edit: The -p parameter is also very useful. It accepts "plain" hexadecimal values, but ignores whitespace and line changes.

So, if you have a plain text dump like this:

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



回答2:


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

Its 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 pipe it using 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

Generate your binary file file.bin:

$ ./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



回答3:


In addition of xxd, you should also look at the packages/commands od and hexdump. All are similar, however each provide slightly different options that will allow you to tailor the output to your desired needs. For example hexdump -C is the traditional hexdump with associated ASCII translation along side.



来源:https://stackoverflow.com/questions/28242813/how-to-convert-a-text-file-to-binary-file-using-linux-commands

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!