Thursday, June 02, 2011

Writing binary files with bash

Hello,
I'm trying to see if I'm able to write some binary file using bash. So, when writing a binary file you often want to write a number into binary format. I ended up with this simple function for writing numbers in little endian:

function num2bin() {
printf $(printf %.$(($2*2))x\\n $1|
sed 's/\([0-9a-f][0-9a-f]\)/\\x\1/g')|
awk -F '' '{ printf $4$3$2$1 }'
}


The first parameter is the number to write, the second is the number of bytes (up to 4). For example "num2bin 40 4" will output a 4-byte long string containing the number 40 in little endian.

How do we use it? I wrote an example script for creating a wav file with noise (according to wav specifications) that you can read here.

Let me know if you have a simpler version of the num2bin function.

4 comments:

Tinyjapanesegirl said...

Thanks, man! That saved my day.

Thetechie find said...

Good article thanks for share information

Black light app
Random Email Generator
How much does a gallon of water weigh
Mybpcreditcard
How to put music on YouTube videos without copyright issues
Price Chopper Direct Connect
How to hide whatsapp online status

pandith13 said...

Nice pick. it's very Useful Article.
SRI ANNAPOORNESHAWARI ASTROLOGY CENTER.Best Astrologer In Maryland

Vasudeva said...

This is a good article. Thanks for sharing

SRIKRISHANA ASTROLOGY .Black Magic Astrologer in Udupi