Skip to content

Instantly share code, notes, and snippets.

@acook
Last active December 23, 2015 10:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acook/6622270 to your computer and use it in GitHub Desktop.
Save acook/6622270 to your computer and use it in GitHub Desktop.
List of gems useful for parsing/generating binary data from Ruby.

Binary Data

It can be challenging to use Ruby for handling raw binary data, involving a lot of Array#pack and String#unpack with the possibility of String#ord and Numeric#chr for good measure. Some of these tools might make the job a bit easier, allowing your to define schemas of the binary data and how to parse it, or even just allowing your to specify the format in a more verbose way.

Gems

BinData

Example

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}"

Packable

Example

["answer", 42].pack({:bytes => 3}, {:bytes => 2, :endian => :big})

BitStruct

Example

class IP < BitStruct
  unsigned    :ip_v,     4,     "Version"
  unsigned    :ip_hl,    4,     "Header length"
  unsigned    :ip_tos,   8,     "TOS"
  unsigned    :ip_len,  16,     "Length"
  unsigned    :ip_id,   16,     "ID"
  unsigned    :ip_off,  16,     "Frag offset"
  unsigned    :ip_ttl,   8,     "TTL"
  unsigned    :ip_p,     8,     "Protocol"
  unsigned    :ip_sum,  16,     "Checksum"
  octets      :ip_src,  32,     "Source addr"
  octets      :ip_dst,  32,     "Dest addr"
  rest        :body,            "Body of message"

  note "     rest is application defined message body"

  initial_value.ip_v    = 4
  initial_value.ip_hl   = 5
end

Arpie

Example

class MyBinary < Arpie::Binary
  uint8 :status
  string :name, :sizeof => :uint8
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment