如何使用 Bash 创建二进制文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8521240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create binary file using Bash?
提问by mustafa
How can I create a binary file with consequent binary values in bash?
如何在 bash 中创建带有后续二进制值的二进制文件?
like:
喜欢:
$ 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 ....
In C, I do:
在 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);
this is what I wanted:
这就是我想要的:
#! /bin/bash
i=0
while [ $i -lt 256 ]; do
h=$(printf "%.2X\n" $i)
echo "$h"| xxd -r -p
i=$((i-1))
done
回答by zhaorufei
There's only 1 byte you cannot pass as argument in bash command line: 0 For any other value, you can just redirect it. It's safe.
只有 1 个字节不能在 bash 命令行中作为参数传递: 0 对于任何其他值,您可以重定向它。它是安全的。
echo -n $'\x01' > binary.dat
echo -n $'\x02' >> binary.dat
...
For the value 0, there's another way to output it to a file
对于值 0,还有另一种方式将其输出到文件
dd if=/dev/zero of=binary.dat bs=1c count=1
To append it to file, use
要将其附加到文件,请使用
dd if=/dev/zero oflag=append conv=notrunc of=binary.dat bs=1c count=1
回答by Cédric Julien
回答by daouzli
If you don't mind to not use an existing command and want to describe you data in a text file, you can use binmakethat is a C++ program that you can compile and use like following:
如果您不介意不使用现有命令并希望在文本文件中描述您的数据,您可以使用binmake,它是一个 C++ 程序,您可以编译和使用,如下所示:
First get and compile binmake(the binary will be in bin/
):
首先获取并编译binmake(二进制文件将在 中bin/
):
$ git clone https://github.com/dadadel/binmake
$ cd binmake
$ make
Create your text file file.txt
:
创建您的文本文件file.txt
:
big-endian
00010203
04050607
# separated bytes not concerned by endianess
08 09 0a 0b 0c 0d 0e 0f
Generate your binary file file.bin
:
生成你的二进制文件file.bin
:
$ ./binmake file.txt file.bin
$ hexdump file.bin
0000000 0100 0302 0504 0706 0908 0b0a 0d0c 0f0e
0000008
Note: you can also use it with stdin/stdout
注意:您也可以将它与 stdin/stdout 一起使用
回答by Prashant Adlinge
use below command,
使用下面的命令,
i=0; while [ $i -lt 256 ]; do echo -en '\x'$(printf "%0x" $i)'' >> binary.dat; i=$((i+1)); done