如何使用 linux 命令将文本文件转换为二进制文件

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

我有文本(字符串)格式的二进制十六进制代码。如何使用 cat 和 echo 等 linux 命令将其转换为二进制文件?

我知道命令后面的命令会创建一个二进制文件 test.bin。但是如果这个 hexcode 在另一个 .txt 文件中呢?如何 "cat" 文本文件的内容到 "echo" 并生成二进制文件?

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

使用xxd -r。它将 hexdump 恢复为其二进制表示形式。

source and source

编辑-p参数也很有用。它接受 "plain" 十六进制值,但忽略空格和换行。

因此,如果您有这样的纯文本转储:

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

您可以将其转换为二进制文件:

xxd -r -p text_dump > binary_dump

然后通过类似以下内容获得有用的输出:

xxd binary_dump

除了xxd,你还应该看看packages/commandsodhexdump。所有这些都是相似的,但是每个都提供略有不同的选项,使您可以根据自己的需要定制输出。例如 hexdump -C 是传统的 hexdump,带有相关联的 A​​SCII 翻译。

如果您有长文本或文件中的文本,您还可以使用 binmake 工具,该工具允许您以文本格式描述一些二进制数据并生成二进制文件(或输出到标准输出)。它允许更改字节顺序和数字格式并接受评论。

其默认格式为十六进制但不限于此。

首先获取编译binmake:

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

您可以使用 stdinstdout:

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

或者使用文件。所以创建你的文本文件 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

生成二进制文件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