Binaries and Pattern Matching

The first rule of binaries is “if in doubt, specify the type of each field.” Available types are binary, bits, bitstring, bytes, float, integer, utf8, utf16, and utf32. You can also add qualifiers:

  • size(n): The size in bits of the field.

  • signed or unsigned: For integer fields, should it be interpreted as signed?

  • endianness: big, little, or native.

Use hyphens to separate multiple attributes for a field:

 
<< length::unsigned-integer-size(12), flags::bitstring-size(4) >> = data

However, unless you’re doing a lot of work with binary file or protocol formats, the most common use of all this scary stuff is to process UTF-8 strings.

String Processing with Binaries

When we process lists, we use patterns that split the ...

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.