14

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
4

4 に答える 4

18

bash コマンド ラインで引数として渡すことができないバイトは 1 つだけです: 0 他の値の場合は、リダイレクトするだけです。安全です。

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

値0の場合、ファイルに出力する別の方法があります

dd if=/dev/zero of=binary.dat bs=1c count=1 

ファイルに追加するには、使用します

dd if=/dev/zero oflag=append conv=notrunc of=binary.dat bs=1c count=1
于 2012-01-12T07:35:47.757 に答える
2

既存のコマンドを使用せず、データをテキスト ファイルに記述したい場合は、次のようにコンパイルして使用できる C++ プログラムであるbinmakeを使用できます。

最初にbinmakeを取得してコンパイルします(バイナリは にありますbin/):

$ git clone https://github.com/dadadel/binmake
$ cd binmake
$ make

テキスト ファイルを作成しますfile.txt

big-endian
00010203
04050607
# separated bytes not concerned by endianess
08 09 0a 0b 0c 0d 0e 0f

バイナリ ファイルを生成しますfile.bin

$ ./binmake file.txt file.bin
$ hexdump file.bin
0000000 0100 0302 0504 0706 0908 0b0a 0d0c 0f0e               
0000008

注: stdin/stdout でも使用できます

于 2016-06-17T13:35:17.023 に答える