How To Pattern Match Bitstrings And Binaries In Elixir — Tentamen Software Testing Blog

String Pattern Matching


In the previous post, we explained how to pattern-match Elixir Maps. Today we explain how to pattern-match Elixir Bitstrings and Binaries. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.

Bitstrings And Binaries

First, we need to recap on bitstrings and binaries. Bitstrings are a chunk of bits with configurable size, while binary is a bitstring with a byte size (eight bits). Remember that Elixir Strings are binaries.

Using binary syntax and pattern-matching operator, we first pattern-match each byte of three-byte binary into separate variables in the above screenshot.

Then we forced one MatchError.

We can pattern-match just what is interesting for us.

It is also possible to pattern-match binary data in smaller chunks of bits. 156 in binary is "10011100". When we split it into two four-bit values, we split 156 into 9 and 12 because 9 => "1001" and 12 => "1100". Note that we used Integer.to_string it because Elixir Strings are binaries.

Let’s pattern match Croatian letters. Š Đ and Č. For them, we need 16 bytes because those are encoded using. Decimal UTF8 value for Š is 50592.

We could also do something like regular expressions with the help of operator. Here we store the testers name into name variable.

When To Use It

When should you use binaries pattern-matching in Elixir? When you are receiving a stream of binary data (zeros and ones) from a file, device, or URL, extracting bits from those streams based on various patterns is best done using binary pattern-matching.


  • binaries pattern matching
  • string pattern matching
  • pattern matching instead of regex

Originally published at on January 22, 2021.




Founder of Tentamen, software testing agency.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Mamp Pro 4 2 1

4.2.1 iphone

Google I/O 2017 Wrap-Up #1: Play Console

Day 20 — Loading Scenes in Unity

Deque in Python

From the design pattern of the metaclass, we easily can take the metaclass as a class-factory for…

Should developers stick to one Programming Language?

CS371 Summer 2021: Blog 4

Using ‘var’ in C# — a pragmatic approach

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Karlo Smid

Karlo Smid

Founder of Tentamen, software testing agency.

More from Medium

Elixir and Ecto

An opinionated Elixir Style Guide #2

Ranked data with Ecto window Queries

Elixir’s best practices: Achieve secure authentication