Bitstrings: Processing Bit-Level Data

Pattern matching on bitstrings works at a bit level, so we can pack and unpack sequences of bits into a bitstring in a single operation. This is extremely useful when writing code that needs to manipulate bit-level data, such as with data that is not aligned to 8-bit boundaries, or variable-length data, where the data length is expressed in bits rather than bytes.

We can illustrate bit-level processing in the shell.

 
1>​ B1 = <<1:8>>.
 
<<1>>
 
2>​ byte_size(B1).
 
1
 
3>​ is_binary(B1).
 
true
 
4>​ is_bitstring(B1).
 
true
 
5>​ B2 = <<1:17>>.
 
<<0,0,1:1>>
 
6>​ is_binary(B2).
 
false
 
7>​ is_bitstring(B2).
 
true
 
8>​ byte_size(B2).
 
3
 
9>​ bit_size(B2).
 
17

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.