Binaries are contiguous byte sequences. Pattern-match them with <<>>: <<b1, b2, rest::binary>> = <<1, 2, 3, 4>> binds the first two bytes and the remainder.
Elixir Easy · Lesson 1 · On the house
Binary pattern matching
<<>>, size/unit, utf8 segments. Lesson 1 is free — on the house.
Lessons · Elixir Easy · Lesson 1 of 10 · On the house
Binary pattern matching
<<>>, size/unit, utf8 segments.

Specify width with size: <<n::size(16)>> matches 16 bits. Default integer segments are unsigned big-endian. Use unit:8 when you want size counted in bytes.
UTF-8 code points use utf8: <<c::utf8, rest::binary>> = "Ábc" binds the first code point. A binary (or bytes) rest segment matches remaining bytes.
Construct binaries the same way: <<1, 2, "hi"::utf8>>. Strings are UTF-8 binaries, so binary patterns apply to "..." values when the shape fits.
Misses: treating <<a, b>> like a tuple {a, b}, forgetting ::binary for a rest segment, or matching utf8 against arbitrary non-UTF-8 bytes.
binaries
<<b1, b2, rest::binary>> = <<1, 2, 3, 4>>
<<n::size(16)>> = <<0, 7>>
<<c::utf8, _::binary>> = "Áx"
IO.inspect({b1, b2, rest, n, c})Quiz
What does <<b1, b2, rest::binary>> match?
Quiz
What does <<n::size(16)>> specify?
Quiz
What does <<c::utf8>> extract?
Quiz
Are Elixir strings binaries?
Check
Match the still for: Binary pattern matching.
Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.