在bash中创建二进制文件

mus*_*afa 12 bash hexdump binaryfiles

如何在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 ....
Run Code Online (Sandbox Code Playgroud)

在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);
Run Code Online (Sandbox Code Playgroud)

这就是我想要的:

#! /bin/bash
i=0
while [ $i -lt 256 ]; do
    h=$(printf "%.2X\n" $i)
    echo "$h"| xxd -r -p
    i=$((i-1))
done
Run Code Online (Sandbox Code Playgroud)

zha*_*fei 14

在bash命令行中只有1个字节无法作为参数传递:0对于任何其他值,您只需重定向即可.它是安全的.

echo -n $'\x01' > binary.dat
echo -n $'\x02' >> binary.dat
...
Run Code Online (Sandbox Code Playgroud)

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

dd if=/dev/zero of=binary.dat bs=1c count=1 
Run Code Online (Sandbox Code Playgroud)

要将其附加到文件,请使用

dd if=/dev/zero oflag=append conv=notrunc of=binary.dat bs=1c count=1
Run Code Online (Sandbox Code Playgroud)

  • 只是 `dd if=/dev/zero bs=1 count=1` 没有 `of` 和 `oflag` 将 `NUL` 字节输出到 stdout。所以你可以做一个`&gt;`或`&gt;&gt;`。 (2认同)

Céd*_*ien 9

也许你可以看看xxd:

xxd :创建给定文件或标准输入的十六进制转储.它还可以将十六进制转储转换回其原始二进制形式.

  • 对于那些想要知道如何使用`xxd`编写而不必离开并查找它的人(就像我不得不):`echo"0000400:4142 4344"| xxd -r - data.bin`其中`0000400`是文件中的字节偏移量,十六进制字节"41"到"44"是写入的内容(嵌入空间被忽略).此示例将字符串'ABCD'以1024字节写入文件'data.bin'. (3认同)