Elixir Language Binaries and Bitstrings


Example

Binaries in elixir are created using the Kernel.SpecialForms construct <<>>.

They are a powerful tool which makes Elixir very useful for working with binary protocols and encodings.

Binaries and bitstrings are specified using a comma delimited list of integers or variable values, bookended by "<<" and ">>". They are composed of 'units', either a grouping of bits or a grouping of bytes. The default grouping is a single byte (8 bits), specified using an integer:

<<222,173,190, 239>> # 0xDEADBEEF

Elixir strings also convert directly to binaries:

iex> <<0, "foo">>
<<0, 102, 111, 111>>

You can add "specifiers" to each "segment" of a binary, allowing you to encode:

  • Data Type
  • Size
  • Endianness

These specifiers are encoded by following each value or variable with the "::" operator:

<<102::integer-native>>
<<102::native-integer>> # Same as above
<<102::unsigned-big-integer>>
<<102::unsigned-big-integer-size(8)>>
<<102::unsigned-big-integer-8>> # Same as above
<<102::8-integer-big-unsigned>>
<<-102::signed-little-float-64>> # -102 as a little-endian Float64
<<-102::native-little-float-64>> # -102 as a Float64 for the current machine

The available data types you can use are:

  • integer
  • float
  • bits (alias for bitstring)
  • bitstring
  • binary
  • bytes (alias for binary)
  • utf8
  • utf16
  • utf32

Be aware that when specifying the 'size' of the binary segment, it varies according to the 'type' chosen in the segment specifier:

  • integer (default) 1 bit
  • float 1 bit
  • binary 8 bits