How to create a binary file using Bash?

How can I create a binary file followed by binary values ​​in 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:

 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 
+11
bash binaryfiles hexdump
source share
4 answers

You cannot pass only 1 byte as an argument on the bash command line: 0 For any other value, you can simply redirect it. It's safe.

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

For value 0, there is another way to output it to a file

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

To add it to a file, use

 dd if=/dev/zero oflag=append conv=notrunc of=binary.dat bs=1c count=1 
+13
source share

Perhaps you can take a look at xxd :

xxd : creates a hex dump of the specified file or standard input. It can also convert a hex dump back to its original binary form.

+8
source share

If you do not mind using the existing command and want to describe your data in a text file, you can use binmake is a C ++ program that you can compile and use as follows:

First get and compile binmake (the binary will be in bin/ ):

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

Create your text file file.txt :

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

Create your binary file.bin file:

 $ ./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

+2
source share

use the command below

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

All Articles