Binaries and bitstrings

A binary in Elixir is a sequence of bytes written between << and >>, and a bitstring is the same container when its length is not a whole number of bytes. Every string the course has used so far is a binary: the bytes of its UTF-8 text. This lesson works at that level, where a header is three bytes and a protocol message is a pattern.

The bitstring literal

The literal takes bytes as integers, and each segment may state its width in bits with ::. byte_size/1 counts the bytes of a binary and bit_size/1 counts the bits of any bitstring:

literal.exs

binary = <<1, 2, 3>> IO.inspect(binary) IO.puts(byte_size(binary)) bits = <<1::4, 2::4>> IO.inspect(bits) IO.puts(bit_size(bits))

elixir literal.exs

<<1, 2, 3>>
3
<<18>>
8

The second value packs two four-bit numbers into one byte: 1 and 2 become 18 in decimal, and the inspector prints the byte it produced. A bitstring whose size is not a multiple of eight cannot be a binary, and byte_size/1 refuses it; bit_size/1 answers for both.

Segments, size and type

A segment has a value, a size and a type. The sizes of a pattern add up to the length of the value, and the last segment can take whatever is left with binary or binary-size(n):

segments.exs

<<a::8, b::16>> = <<1, 0, 2>> IO.inspect({a, b}) <<x::size(4), y::size(4)>> = <<0xAB>> IO.inspect({x, y}) <<first::binary-size(2), rest::binary>> = "hello" IO.inspect({first, rest})

elixir segments.exs

{1, 2}
{10, 11}
{"he", "llo"}

The default size of an integer segment is eight bits, so ::8 and ::size(8) are the same, and a 16-bit segment reads two bytes in the order they appear. The hex literal 0xAB is the ordinary integer 171, written in the base a protocol document uses.

A binary in a function head

The bitstring pattern is also a function head, which is how a parser reads a message without indexes or loops. The clause below takes a version byte, a two-byte length and the rest of the message:

parse.exs

defmodule Packet do def parse(<<version::8, length::16, body::binary>>) do {version, length, body} end end IO.inspect(Packet.parse(<<1, 0, 3, "abc">>)) IO.inspect(Packet.parse(<<2, 0, 0>>))

elixir parse.exs

{1, 3, "abc"}
{2, 0, ""}

The last call shows the empty body: a binary segment matches zero bytes, which is why a message with no payload still fits the pattern. A second clause with a shorter pattern would handle a message that is only a header, and a check of byte_size(body) == length in a guard is where a parser refuses a message it cannot trust.

Building a binary

The same syntax builds a value: segments concatenate, and ::binary puts a whole binary inside the result. The double angle operator is a shorthand for two strings, and ?a is the code point of one character:

build.exs

name = "Ada" IO.inspect(<<"hi ", name::binary>>) IO.inspect("a" <> "b") IO.inspect(<<?a, ?b, ?c>>) IO.inspect(byte_size(<<"hi ", name::binary>>))

elixir build.exs

"hi Ada"
"ab"
"abc"
6

The inspector shows a valid UTF-8 binary as a string and a binary of arbitrary bytes as <<...>>, which is the signal that the value is not text. The <> operator concatenates two binaries and raises when one side is not a binary; the bitstring form takes mixed segments, such as a number and a string, in one call.

A code point as bytes

The utf8 type reads and writes the UTF-8 encoding of a code point, which is the bridge between the two views of the same text:

utf8.exs

<<code::utf8>> = "é" IO.puts(code) IO.inspect(<<233::utf8>>) IO.inspect(<<233::utf8>> == "é")

elixir utf8.exs

233
"é"
true

é is the code point 233 and two bytes, 195 and 169, and the utf8 type converts between them. The Unicode lesson of this part goes further into the encodings; the charlists that Erlang calls strings have their own lesson too.

The mistake: a segment the data cannot fill

A fixed size in the pattern is a promise about the data. When the binary is shorter, the match fails and the program stops with a MatchError that prints the value it was given:

mistake.exs

<<a::16>> = <<1>> IO.inspect(a)

elixir mistake.exs

** (MatchError) no match of right hand side value:

    <<1>>

    mistake.exs:1: (file)
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

A parser that meets a truncated message should decide what that means rather than crash: a clause for the short value, a guard on byte_size/1, or a pattern with rest::binary that accepts the shorter tail. A protocol header is a promise the network does not keep, which is why the size is checked before the fields are read.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the difference between a binary and a bitstring?

    Answer

    A binary is a bitstring whose size is a multiple of eight bits

    Every binary is a bitstring, and a bitstring is a binary when its bit size divides by eight.

  2. Which call counts the bits of a bitstring?

    Answer

    bit_size/1

    bit_size/1 answers for every bitstring, while byte_size/1 is the byte view.

  3. What does the utf8 type do in a segment?

    Answer

    It reads or writes the UTF-8 encoding of a code point

    The type turns a code point into its UTF-8 bytes and back, which is the bridge to a string.

  4. What does ?a mean in a bitstring literal?

    Answer

    the code point 97

    The question mark takes the code point of the character that follows.

  5. What does this program print? IO.inspect(<<1::4, 2::4>>)

    Answer

    <<18>>

    The two four-bit numbers share one byte, which is 18 in decimal.

  6. What does this program print? <<a::16>> = <<1, 2>> IO.inspect(a)

    Answer

    258

    The two bytes form one 16-bit number: 1 256 + 2 is 258.

  7. What does this program print? <<x::4, y::4>> = <<0xAB>> IO.inspect({x, y})

    Answer

    {10, 11}

    The byte 0xAB splits into the high nibble 10 and the low nibble 11.

  8. What does this program print? <<first::binary-size(2), rest::binary>> = "hello" IO.inspect({first, rest})

    Answer

    {"he", "llo"}

    The first segment takes two bytes and rest takes all that is left.

  9. What does this program print? IO.inspect(<<?a, ?b>>)

    Answer

    "ab"

    Two ASCII code points make a valid UTF-8 binary, which the inspector shows as a string.

  10. What does this program do? <<a::16>> = <<1>> IO.inspect(a)

    Answer

    A MatchError, because the binary has one byte and the segment wants two

    A fixed size in the pattern must fit the value, and a short binary does not match.

Article author: Arthur Isaev