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

Navigation


Quick Start

Stop writing code like this.

def read_fancy_format(io)
  comment, len, rest = io.read.unpack("Z*Ca*")
  data = rest.unpack("N#{len}")
  {:comment => comment, :len => len, :data => *data}
end

Instead, write code like this.

class MyFancyFormat < BinData::Record
  stringz :comment
  uint8   :len
  array   :data, type: :int32be, initial_length: :len
end

Creating a Record

Start by subclassing BinData::Record.

class MyFancyFormat < BinData::Record
end

Begin to add fields for each attribute of the file format.

class MyFancyFormat < BinData::Record
  stringz :comment
end

Most fields will be primitive types (numbers and strings).

class MyFancyFormat < BinData::Record
  stringz :comment
  uint8   :len
end

You will also use compound types such as arrays, nested records or choices, as well as parameters specifying dependent fields.

class MyFancyFormat < BinData::Record
  stringz :comment
  uint8   :len, value: -> { data.length }
  array   :data, type: :int32be, initial_length: :len
end

Once you're created your new subclass, there are common operations to perform.

class MyFancyFormat < BinData::Record
  stringz :comment
  uint8   :len, value: -> { data.length }
  array   :data, type: :int32be, initial_length: :len
end

obj = MyFancyFormat.new
obj.comment = "this is my comment"
obj.data = [2, 4, 6]
obj.to_binary_s #=> "this is my comment\x00\x03\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00\x06"

Clone this wiki locally