【问题标题】:How to convert a text file to binary file using linux commands如何使用linux命令将文本文件转换为二进制文件
【发布时间】:2015-03-30 08:05:54
【问题描述】:

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

我知道创建二进制 test.bin 的命令之后的命令。但是如果这个十六进制代码在另一个 .txt 文件中呢?如何将文本文件的内容“cat”到“echo”并生成二进制文件?

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

【问题讨论】:

    标签: linux shell unix command-line


    【解决方案1】:

    使用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
    

    【讨论】:

    • 在一个班轮中:xxd -r -p <(echo "0A 04 00 00 34") | xxd
    • 我该如何扭转上述动作?如:xxd -r -p text_dump > binary_dump 给了我一个文件(binary_dump)。如何恢复将 binary_dump 转换为 text_dump 的操作??
    • @EllyAmbet 你可以使用 xxd -p binary_dump > text
    【解决方案2】:

    除了xxd,您还应该查看包/命令odhexdump。所有都是相似的,但是每个都提供略有不同的选项,可让您根据所需的需求定制输出。例如,hexdump -C 是传统的 hexdump,旁边带有相关的 ASCII 翻译。

    【讨论】:

      【解决方案3】:

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

      它的默认格式是十六进制但不限于此。

      首先获取并编译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
      

      【讨论】:

      • 在我的 linux 上不起作用猜测需要安装依赖项
      • @JacquelineP。什么依赖?它是一个 C++11 开源程序,因此它当然依赖于 g++ 编译器,但没有外来库。只使用标准库(因为我记得正则表达式是标准)。
      猜你喜欢
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 2016-03-30
      • 2019-08-21
      • 2014-07-30
      • 2010-09-30
      相关资源
      最近更新 更多