Binaries

Get familiar with the use of binaries in Elixir.

We'll cover the following

Binaries

The binary type represents a sequence of bits. A binary literal looks like << term,... >>. The simplest term is just a number from 0 to 255. The numbers are stored as successive bytes in the binary.

iex> b = << 1, 2, 3 >> 
<<1, 2, 3>>

iex> byte_size b
3

iex> bit_size b 
24

We can specify modifiers to set any term’s size (in bits). This is useful when working with binary formats such as media files and network packets.

iex> b = << 1::size(2), 1::size(3) >>  # 01 001
<<9::size(5)>>     # = 9 (base 10)

iex> byte_size b  
1

iex> bit_size b 
5

We can store integers, floats, and other binaries in binaries.

iex> int = << 1 >>
<<1>>

iex> float = << 2.5 :: float >>
<<64, 4, 0, 0, 0, 0, 0, 0>>

iex> mix = << int :: binary, float :: binary >> 
<<1, 64, 4, 0, 0, 0, 0, 0, 0>>

Get hands-on with 1400+ tech skills courses.