May 2018
Intermediate to advanced
412 pages
9h 3m
English
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 ... |
Read now
Unlock full access