Cover by Francesco Cesarini, Simon Thompson

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

O'Reilly logo

Binaries and Serialization

Sometimes large amounts of structured data have to be transferred between computers or stored. How should protocols ensure that data is generated and transmitted as quickly and efficiently as possible? The answer is to make use of every possible bit of storage, packing the bits in each word with as much information as possible. Erlang binaries give a pattern-matching notation for manipulating binary data structures, making this kind of lower-level programming easier, robust, and more space efficient than using tuples or lists. In addition to binaries, in the following subsections we will also look at efficient ways that high-level, nonflat data structures can be serialized and deserialized, using trees as an example.

Binaries

A binary is a reference to a chunk of raw, untyped memory. It was originally used by the Erlang runtime system for loading code over the network, but was quickly applied in a more generic setting of socket-based communication. Binaries are effective in moving large amounts of data, with BIFs provided for coding, decoding, and binary manipulation to this extent:

1> Bin1 = term_to_binary({test,12,true,[1,2,3]}).
<<131,104,4,100,0,4,116,101,115,116,97,12,100,0,4,116,114,
  117,101,107,0,3,1,2,3>>
2> Term1 = binary_to_term(Bin1).
{test,12,true,[1,2,3]}
3> Bin2 = term_to_binary({cat,dog}).
<<131,104,2,100,0,3,99,97,116,100,0,3,100,111,103>>
4> Bin3 = list_to_binary([Bin1, Bin2]). <<131,104,4,100,0,4,116,101,115,116,97,12,100,0,4,116,114, 117,101,107,0,3,1,2,3,131,104,2,100,...>> ...

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