如何使用Bash创建二进制文件?

如何使用Bash创建二进制文件?

问题描述:

如何在bash中创建具有相应二进制值的二进制文件?

How can I create a binary file with consequent binary values in 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语言中,我这样做:

In C, I do:

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

在bash命令行中,只有1个字节不能作为参数传递:0 对于其他任何值,您都可以重定向它.很安全.

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.

echo -n $'\x01' > binary.dat
echo -n $'\x02' >> binary.dat
...

对于值0,还有另一种将其输出到文件的方法

For the value 0, there's another way to output it to a file

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