Matching on binaries
  •  1 min read

Matching on bitstrings can be used to parse bits and bytes out of a binary.

Example data is the Legend of Zelda NES ROM header:

header = <<0x4E, 0x45, 0x53, 0x1A, 0x08, 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00>>

Matching bytes

Simply use the entire byte representation. Characters, hexadecimal numbers, decimal numbers, etc.

<<"N" , "E" , "S" , 0x1A, program_banks, graphics_banks, _rest::binary>> = header

dbg(program_banks) # => 8
dbg(graphics_banks) # => 0

Matching different sizes of bits

Use ::size to denote the number of bits you want to match on

<<_already_parsed_above::48,
  lower_mapper::4,
  four_screen_mirroring::1,
  trainer_present::1,
  battery_backed_ram::1,
  mirroring::1,
  upper_mapper::4,
  _unused::4,
  _rest::binary>> = header

dbg(lower_mapper) # => 1
dbg(upper_mapper) # => 0 
dbg(battery_backed_ram) # => 1