liveBook · Manning

Binary string

As explained in Elixir in Action, Third Edition

A binary is a contiguous sequence of bytes used by Elixir to represent binary data and strings.

A binary is a contiguous sequence of bytes. Elixir has no dedicated string type, so double-quoted strings are binaries underneath and can be concatenated with <>. section 2.4.7 section 2.4.8

Build and use binary strings with these core operations:

  • Construct byte sequences with <<...>>; values exceeding one byte are truncated unless an explicit bit size is supplied. section 2.4.7
  • Combine binaries with <> and use interpolation, escapes, sigils, and heredocs for string syntax. section 2.4.8
  • Prefer binary strings over character lists for ordinary text; use String functions for character-oriented operations. section 2.4.8
  • Use binary pattern matching to extract bytes, bit fields, or a suffix beginning after a known binary prefix. section 3.1.7

Parse a command prefix

command = "ping www.example.com" "ping " <> url = command url # "www.example.com" section 3.1.7

iex(8)> <<1, 2>> <> <<3, 4>>
<<1, 2, 3, 4>>

Concatenate binary values directly and inspect the resulting byte sequence. section 2.4.7

iex(3)> iolist = []                             #1
iolist = [iolist, "This"]                       #2
iolist = [iolist, " is"]                        #2
iolist = [iolist, " an"]                        #2
iolist = [iolist, " IO list."]                  #2
 
[[[[[], "This"], " is"], " an"], " IO list."]   #3

Assemble output incrementally with nested IO lists when repeated binary construction would be inefficient. section 2.4.12

How Elixir in Action, Third Edition covers it

How deep it goes
Defines construction, sizing, concatenation, and basic matching, but defers extensive binary handling and Unicode character processing.
Examples
Uses byte literals, sized bit fields, concatenated binaries, command-prefix matching, and nested IO-list output.
What you can do after
Apply it via Elixir syntax to construct, concatenate, match, and route byte sequences to I/O functions.
How it connects
Connects binaries with bitstrings, strings, character lists, pattern matching, the String module, and IO lists.

Also explained in

Compare how 5 books explain binary string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.