Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write binary file in Ruby

Tags:

ruby

Is there a simple way to write binary data into binary file like we used to do in C/C++? For example, how can I create a 4-byte file with serialized 4-byte integer value without using fancy math?

like image 891
Alex Kovshovik Avatar asked Jun 02 '09 20:06

Alex Kovshovik


People also ask

What is inside a binary file?

A binary file is a file whose content is in a binary format consisting of a series of sequential bytes, each of which is eight bits in length. The content must be interpreted by a program or a hardware processor that understands in advance exactly how that content is formatted and how to read the data.

What is packed binary data?

In data structures, packed binary data usually means that more (if not all available) bit combinations are used to encode some values, while unpacked means that some bit combinations remain unused, either to improve readability or to make certain calculations easier (but unpacked data takes more space).

What is unpack in Ruby?

unpack(p1) public. Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry.


2 Answers

You can use Array#pack and String#unpack to convert to and from binary representations. Combine them with IO#write and IO#read, and away you go.

like image 173
Pesto Avatar answered Oct 05 '22 23:10

Pesto


I recently had a similar problem for work. I used the BinData gem and it worked a treat. You just do something like:

File.open('test.bin', 'wb') {|file| BinData::Int32be.new(12345).write(file) } 

and you don't need to remember any Array#pack codes.

like image 38
Jason Avatar answered Oct 05 '22 22:10

Jason