Fylke
January 31, 2023, 10:42am
1
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
phild
January 31, 2023, 1:56pm
2
A trivial example I used in Advent of Code:
parse(<<"noop">>) -> noop;
parse(<<"addx ", V/binary>>) -> {addx, binary_to_integer(V)}.
1 Like
sverker
February 10, 2023, 9:18am
3
These two examples do not work:
<<A/big>> = <<255, 0>>
255
<<A/little>> = <<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/little>> = <<255, 0>>
255
4 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
Fylke
February 15, 2023, 3:04pm
6
Oooh, good one, thanks! I’ll fix that
3 Likes