[英]create binary file in bash
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
There's only 1 byte you cannot pass as argument in bash command line: 0 For any other value, you can just redirect it. 在bash命令行中只有1个字节无法作为参数传递:0对于任何其他值,您只需重定向它即可。 It's safe. 它是安全的。
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
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: 如果您不介意不使用现有命令并希望在文本文件中描述数据,则可以使用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一起使用
使用下面的命令,
i=0; while [ $i -lt 256 ]; do echo -en '\x'$(printf "%0x" $i)'' >> binary.dat; i=$((i+1)); done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.