web-dev-qa-db-ja.com

Bashを使用してバイナリファイルを作成するにはどうすればよいですか?

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
13
mustafa

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
16
zhaorufei

たぶんあなたは xxd を見てみることができます:

xxd:指定されたファイルまたは標準入力の16進ダンプを作成します。また、16進ダンプを元のバイナリ形式に戻すこともできます。

9
Cédric Julien

既存のコマンドを使用せずにテキストファイルでデータを記述したい場合は、次のようにコンパイルして使用できる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でも使用できます

2
daouzli

以下のコマンドを使用して、

i=0; while [ $i -lt 256 ]; do echo -en '\x'$(printf "%0x" $i)''  >> binary.dat; i=$((i+1));  done
0