Binaries

Sometimes you need to access data as a sequence of bits and bytes. For example, the headers in JPEG and MP3 files contain fields where a single byte may encode two or three separate values.

Elixir supports this with the binary data type. Binary literals are enclosed between << and >>.

The basic syntax packs successive integers into bytes:

 iex>​ bin = << 1, 2 >>
 <<1, 2>>
 iex>​ byte_size bin
 2

You can add modifiers to control the type and size of each individual field. Here’s a single byte that contains three fields of widths 2, 4, and 2 bits. (The example uses some built-in libraries to show the result’s binary value.)

 iex>​ bin = <<3 :: size(2), 5 :: size(4), 1 :: size(2)>>
 <<213>>
 iex>​ ​:io​.format(​"​​~-8.2b~n"​, ​:binary ...

Get Programming Elixir 1.3 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.