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.
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}"
["answer", 42].pack({:bytes => 3}, {:bytes => 2, :endian => :big})
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
class MyBinary < Arpie::Binary
uint8 :status
string :name, :sizeof => :uint8
end