The Bit Syntax

The bit syntax is a notation used for extracting and packing individual bits or sequences of bits in binary data. When you’re writing low-level code to pack and unpack binary data at a bit level, you’ll find the bit syntax incredibly useful. The bit syntax was developed for protocol programming (something that Erlang excels at) and produces highly efficient code for manipulating binary data.

Suppose we have three variables—X, Y, and Z—that we want to pack into a 16-bit memory area. X should take 3 bits in the result, Y should take 7 bits, and Z should take 6. In most languages this involves some messy low-level operations involving bit shifting and masking. In Erlang, we just write the following:

 
M = <<X:3, Y:7, Z:6>>

This ...

Get Programming Erlang, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.