Erlang Binaries Cheat Sheet

I updated my cheat sheet for binaries: https://cheatography.com/fylke/cheat-sheets/erlang-binaries/

Every time I’m working with binaries, it feels like I’ve forgotten all the related syntax. So I made a cheat sheet. Hopefully you will find it helpful too!

I’m struggling a bit with additional examples of just normal use - any suggestions are welcome!

14 Likes

A trivial example I used in Advent of Code:

parse(<<"noop">>) -> noop;
parse(<<"addx ", V/binary>>) -> {addx, binary_to_integer(V)}.
1 Like

These two examples do not work:

<<A­/bi­g>> = <<255, 0>> 255
<<A­/li­ttl­e>> = <<255, 0>> 65280

You must specify bit count, and the big/little endians are reversed. This works:

<<A­:16/big>> = <<255, 0>> 65280
<<A­:16/li­ttl­e>> = <<255, 0>> 255
4 Likes

Thank you, fixed!

2 Likes

I have a couple of nitpicks about the Segments section:

  • " Value is either a literal or a variable"
  • Size […] can be any expression that evaluates to an integer

The rules are a bit more subtle (and given in Erlang -- Expressions):

  • If the binary is a pattern used for matching
    • Value must indeed be a literal or a variable
    • But Size must be a guard expression
  • If the binary is an expression
    • Size can indeed be any expression that evaluates to an integer
    • But Value can be any expression, as long as it is wrapped in parenthesis.

So for example the following is fine:

f(X) ->
  <<(case X of [] -> 42; _ -> 13 end):16/big>>.

But the following is not:

f(<<X:(foobar())/big>>) ->
  X.
5 Likes

Oooh, good one, thanks! I’ll fix that

3 Likes