Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a binary file using Bash?

Tags:

My problem is that I need to create a file with this exact bytes: 48, 00, 49, 00.

I cannot use C, perl, other scripting language (the target is an embedded device). I tried this using awk, and in desktop it does work:

# awk  'BEGIN{ printf "%c%c%c%c", 48, 00, 49, 00 }' | hexdump 0000000 0030 0031                               0000004 

However the target platform is running busybox v1.13.2 and this code does not work there. The awk version there does not output ascii "0" (all other values are ok).

What are your recommendations?

like image 505
elcuco Avatar asked Apr 07 '11 14:04

elcuco


People also ask

How do you write a binary file?

To write to a binary fileUse the WriteAllBytes method, supplying the file path and name and the bytes to be written. This example appends the data array CustomerData to the file named CollectedData. dat .


2 Answers

you can use the following command:

echo -n -e \\x48\\x00\\x49\\x00 > myfile 
like image 114
yohann.martineau Avatar answered Oct 29 '22 08:10

yohann.martineau


you could try echo, that also allows arbitrary ascii chars (those numbers are octal numbers).

echo -n -e \\0060\\0000\\0061\\0000  | hexdump 
like image 33
flolo Avatar answered Oct 29 '22 09:10

flolo