Skip to content
Dion Mendel edited this page Jun 25, 2023 · 12 revisions

BinData - Reading and Writing Binary Data in Ruby

BinData provides a declarative way to read and write structured binary data.

This means the programmer specifies what the format of the binary data is, and BinData works out how to read and write data in this format. It is an easier (and more readable) alternative to ruby's #pack and #unpack methods.

Navigation

What is it for?

Do you ever find yourself writing code like this?

io = File.open(...)
len = io.read(2).unpack("v")[0]
name = io.read(len)
width, height = io.read(8).unpack("VV")
puts "Rectangle #{name} is #{width} x #{height}"

It's ugly, violates DRY and doesn't feel like Ruby.

There is a better way.

class Rectangle < BinData::Record
  endian :little
  uint16 :len
  string :name, read_length: :len
  uint32 :width
  uint32 :height
end

io = File.open(...)
r = Rectangle.read(io)
puts "Rectangle #{r.name} is #{r.width} x #{r.height}"

BinData makes it easy to specify the structure of the data you are manipulating.

It supports all the common datatypes that are found in structured binary data. Support for dependent and variable length fields is built in.

License

BinData is released under the same license as Ruby.

Copyright © 2007 - 2023 Dion Mendel

Clone this wiki locally