Tech News
← Back to articles

Making the most of bit arrays in Gleam

read original related products more articles

Gleam has a special piece of syntax that most other languages don't: Bit arrays. Taken from Erlang, bit array syntax allows the constructing and pattern matching on binary data. Bit arrays are extremely powerful, but unfortunately the documentation is a little sparse. It lists all the possible options you can use, as well as linking to the Erlang documentation for further reading, but the syntax isn't exactly the same as on Erlang, so there's some ambiguity as to how it exactly works. To make it easier, I wanted to write a comprehensive guide, to make it as easy as possible to understand how they work.

Table of contents

The basics

Bit arrays are delimited by double angle brackets ( << and >> ), and contain zero or more segments, separated by commas. A segment is a value which is encoded somehow as a sequence of bits. They have no actual separation other than syntactically, they are just a way of building up a bit array out of various different parts.

A segment consists of a value, followed by a series of options using the syntax value:option1-option2-option3 .

There are several different data types that can appear as the value of a bit array segment, and each has a slightly different set of defaults, as well as options that can be used to modify how it is encoded.

The default assumed type is Int , and if you want a segment that is a non-integer, you need to specify that by using the type-specific option, unless you are using a literal, in which case it is inferred automatically.

Segment types

As mentioned above, the default segment type is Int . By default, integer segments are encoded as an 8-bit signed integer, although this can be modified using various options, which will be mentioned later.

The syntax for printing bit arrays with the echo keyword uses 8-bit unsigned integer segments to represent the structure of the bit array, so that is what I will be using in the rest of this article to show the encoding of various bit arrays.

... continue reading