O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

You 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) >>
 
<<9::size(5)>>​​
 
iex>​ byte_size b
 
1​​
 
iex>​ bit_size b
 
5

You 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required