如何使用 Bash 创建二进制文件?
如何在 Bash 中创建带有后续二进制值的二进制文件?
就像:
hexdump testfile
0000000 0100 0302 0504 0706 0908 0b0a 0d0c 0f0e
0000010 1110 1312 1514 1716 1918 1b1a 1d1c 1f1e
0000020 2120 2322 2524 2726 2928 2b2a 2d2c 2f2e
0000030 ....
在 C 中,我做:
fd = open("testfile", O_RDWR | O_CREAT);
for (i=0; i< CONTENT_SIZE; i++)
{
testBufOut[i] = i;
}
num_bytes_written = write(fd, testBufOut, CONTENT_SIZE);
close (fd);
这就是我想要的:
#! /bin/bash
i=0
while [ $i -lt 256 ]; do
h=$(printf "%.2X\n" $i)
echo "$h"| xxd -r -p
i=$((i-1))
done
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只有一个字节不能作为 Bash 命令行中的参数传递: 0
对于任何其他值,您可以直接重定向它。很安全。
对于值 0,还有另一种方法将其输出到文件
要将其附加到文件,请使用
There's only one byte you cannot pass as an argument in a Bash command line: 0
For any other value, you can just redirect it. It's safe.
For the value 0, there's another way to output it to a file
To append it to file, use
看看 xxd:
Take a look at xxd:
如果您不介意不使用现有命令并希望在文本文件中描述数据,则可以使用 binmake。这是一个 C++ 程序,您可以像下面这样编译和使用:
首先获取并编译 binmake (二进制文件将位于
bin/
中):创建文本文件
file.txt
:生成二进制文件
file.bin
:注意:您还可以将其与标准输入和标准输出。
If you don't mind to not use an existing command and want to describe you data in a text file, you can use binmake. That is a C++ program that you can compile and use like following:
First get and compile binmake (the binary will be in
bin/
):Create your text file
file.txt
:Generate your binary file
file.bin
:Note: you can also use it with standard input and standard output.
使用以下命令,
Use the below command,
在 Unix 和类 Unix 系统中,开发人员忘记了以前的竞争系统中内置的这种功能(通过 ROM 中的监控程序)。
在该系列系统中,如果不先传输程序,就无法从键盘输入创建二进制文件。
这是因为在当时(20世纪70年代中期),这条路径与竞争路径、用户可访问(解释器)和用户可用(内置)不同。
因此,编译器是在这些系统上创建二进制文件所必需的依赖项,尽管 ROM 中只需要很少的代码字节即可允许用户在任何计算机上输入二进制文件(包括可执行文件)。
In Unix, and Unix-like systems, the developers forgot about this ability built into previous and competing systems (by way of a monitor program in ROM).
There is no way in this family of systems to create a binary file from keyboard input, without first transferring a program to do so.
It is because at the time (mid 1970s), this path diverged from the competing paths, user-accessible (interpreter), and user-usable (built in).
Thus, a compiler is a dependency necessary to create a binary on these systems, even though very few bytes of code is required in ROM to allow a user to enter a binary file, including an executable one, on any computer.