如何使用Linux命令将包含十六进制的文本文件转换为二进制文件?

wj8zmpe1  于 2022-10-17  发布在  Linux
关注(0)|答案(3)|浏览(577)

我有一个文本(字符串)格式的二进制十六进制代码。如何使用CAT和ECHO等Linux命令将其转换为二进制文件?
我知道命令跟在创建二进制文件test.bin的命令后面。但是如果这个十六进制码在另一个.txt文件中呢?我如何“猫”的内容文本文件“回显”和生成一个二进制文件?
# echo -e "x00x001" > test.bin

lnlaulya

lnlaulya1#

使用xxd -r。它将十六进制转储恢复为其二进制表示形式。
sourcesource

编辑-p参数也非常有用。它接受“纯”十六进制值,但忽略空格和行更改。

因此,如果您有一个如下所示的纯文本转储:

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

您可以使用以下命令将其转换为二进制:

xxd -r -p text_dump > binary_dump

然后使用如下内容获得有用的输出:

xxd binary_dump
06odsfpq

06odsfpq2#

如果您有长文本或文件中的文本,您还可以使用binmake工具,该工具允许您以文本格式描述一些二进制数据并生成一个二进制文件(或输出到stdout)。它允许更改字符顺序和数字格式,并接受注解。
其默认格式为十六进制,但不限于此。
首先获取并编译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
5ktev3wc

5ktev3wc3#

除了xxd之外,您还应该查看包/命令odhexdump。它们都是相似的,但每个都提供了略微不同的选项,使您可以根据需要定制输出。例如,hexdump -C是具有关联的ASCII转换的传统六进制转储。

相关问题