These are useful code snippets I've used when working with binary data and don't want to forget them. Some examples are not optimized as much as they could be in order to help keep the functionality clear.

Command Line Script Template

Useful for running a script from the command line.
Used like:
./secret_of_mana_decompress.rb som-font-compressed.gfx som-font-uncompressed.gfx

#!/usr/bin/env ruby
if ARGV.size < 2
  puts("[!] I need both an input file and an output file.")
  exit
end

input_file  = ARGV[0]
output_file = ARGV[1]

puts "[*] Input:       #{ARGV[0]}"
puts "[*] Output:      #{ARGV[1]}"

Reading Header Data

Not specifically for a header, but reading subsequent bytes from a file.

@compression_type
@compressed_data
@uncompressed_size

File.open(input_file, "rb") do |f|
  bytes = f.read(2)
  @compression_type = bytes[1] << 8 | bytes[0]
  puts "[*] Format:      " + "%x" % @compression_type

  bytes = f.read(2)
  @uncompressed_size = bytes[0] << 8 | bytes[1]
  puts "[*] Output Size: " + "%d bytes" % @uncompressed_size

  @compressed_data = f.read()
  puts "[*] Compressed Data:  " + "%d bytes" % @compressed_data.length
end

Viewing Data as Hexadecimal

There are many ways to do this.

@uncompressed_data.map { |x| x.nil? ? '__' : "%02X" % x }.join

Writing data to File

There are many ways to do this.

File.open(output_file, "wb") do |output|
  @uncompressed_data.each do |byte|
    output.print byte.chr
  end
end