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?
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With