Bit syntax
A binary is a sequence of bytes, and the bit syntax is how Erlang builds one and takes it apart. A segment in angle brackets names the value, its size and its type, and the same syntax works in a pattern: the process reads a packet field by field, without an index and without a helper library. This is the feature that makes Erlang a good language for protocols.
Build a binary
A segment takes an integer, a size in bits and a type. With no size a segment is one byte, so a list of small numbers builds a binary directly. The shell prints a binary as the bytes it holds, or as a string when every byte is printable:
erl
1> <<1>>. <<1>> 2> <<255, 0>>. <<255,0>> 3> <<"hi">>. <<"hi">> 4> <<1:8>>. <<1>> 5> <<1:4, 2:4>>. <<18>>
The last line packs two four-bit numbers into one byte: 0001 followed by 0010 is 00010010, the byte 18. A size is measured in bits unless the type says otherwise, and the sizes of the segments decide how the bytes are laid out.
Segments, sizes and types
After the slash comes a list of specifiers separated by dashes: the type (integer, float, binary, bitstring, utf8 and others), the signedness (signed or unsigned), the endianness (big, little or native) and the unit. The defaults are an unsigned big-endian integer with a size in bits:
erl
1> <<1:16>>. <<0,1>> 2> <<1:16/little>>. <<1,0>> 3> <<1:32/float>>. <<63,128,0,0>> 4> <<-1:8>>. <<"ÿ">> 5> <<1:2/unit:8>>. <<0,1>>
unit:8 multiplies the size, so 1:2/unit:8 is two bytes. A negative integer wraps into the unsigned field: -1 in eight bits is the byte 255. The float segment takes an IEEE 754 value and writes its four or eight bytes.
Match a binary
A binary pattern splits the input: a segment with a size takes that many bits, and a segment of type binary takes everything that is left when it has no size. This is how a function head reads a record of fixed fields:
color.erl
-module(color). -export([main/0, red/1]). red(<<R:8, _G:8, _B:8>>) -> R. main() -> Pixel = <<255, 128, 0>>, io:format("~p~n", [Pixel]), io:format("~p~n", [red(Pixel)]).
erlc color.erl
erl -noshell -eval 'color:main(), halt().'
<<255,128,0>> 255
The pattern matches a binary of exactly three bytes, because the three segments are fixed. A binary of another length does not match and the clause is skipped; a function with no matching clause raises function_clause. A trailing Rest/binary keeps the remainder and turns the same head into a parser for one record followed by more data.
A size that truncates
A segment whose size is smaller than the value keeps only the low bits. The compiler does not warn, and the loss shows up as a wrong byte rather than an error:
erl
1> <<300:8>>. <<",">> 2> <<300:16>>. <<1,44>>
The byte 44 is 300 modulo 256. The size is a promise about the field, so a value read from input must be checked against the field width before it is packed, or the packet arrives with a number nobody sent. The same arithmetic explains why a 16-bit field holds 300 as the two bytes 1 and 44.
UTF-8 and the packet format
A utf8 segment writes one character as the bytes UTF-8 needs, and the size of the result depends on the character. Reading it back with the same specifier gives the code point:
codepoint.erl
-module(codepoint). -export([main/0]). main() -> Euro = <<8364/utf8>>, io:format("~p~n", [Euro]), io:format("~p~n", [byte_size(Euro)]).
erlc codepoint.erl
erl -noshell -eval 'codepoint:main(), halt().'
<<226,130,172>> 3
The three bytes are the UTF-8 form of the euro sign. The pattern <<C/utf8, Rest/binary>> takes one character and leaves the rest, which is how a text parser walks a binary without counting bytes itself.
A length-prefixed packet combines the two ideas: a size field, then a payload of that many bytes. The encoder reads the length of the text; the decoder puts the size into the payload segment, so the pattern itself enforces the length:
packet.erl
-module(packet). -export([main/0, encode/1, decode/1]). encode(Text) -> Size = byte_size(Text), <<Size:16, Text/binary>>. decode(<<Size:16, Text:Size/binary>>) -> {ok, Text}; decode(_) -> error. main() -> Packet = encode(<<"hello">>), io:format("~p~n", [Packet]), io:format("~p~n", [decode(Packet)]), io:format("~p~n", [byte_size(Packet)]).
erlc packet.erl
erl -noshell -eval 'packet:main(), halt().'
<<0,5,104,101,108,108,111>> {ok,<<"hello">>} 7
The first two bytes are the length, and the rest is the text; the decoder uses the length as the size of the payload segment. decode/1 has a second clause, so a packet of the wrong shape answers error instead of crashing the process. The Binaries in depth lesson goes on with the sizes, the UTF-8 forms and the iolist that never copies.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a segment with no size hold?
Answer
One byte
The default size of an integer segment is eight bits, one byte.
-
What does
<<1:4, 2:4>>build?Answer
<<18>>The two four-bit fields pack into one byte: 0001 and 0010 make 00010010, which is 18.
-
What does
<<1:16>>produce?Answer
<<0,1>>The default endianness is big, so the value one in sixteen bits is a zero byte then a one byte.
-
Which specifier makes a segment take the rest of the binary?
Answer
/binarywith no sizeA segment of type
binarywith no size matches every remaining byte. -
What does
<<300:8>>build?Answer
<<44>>The field keeps the low eight bits, and 300 modulo 256 is 44.
-
What happens when a binary of another length meets a pattern of fixed segments?
Answer
The pattern does not match and the clause is skipped
A pattern of fixed segments matches only the exact length; unmatched input moves to the next clause or raises
function_clause. -
What does this module print?
-module(q1). -export([main/0]). main() -> io:format("~p~n", [byte_size(<<1:4, 2:4>>)]).Answer
1The two four-bit fields fill one byte, so the binary is one byte long.
-
What does this module print?
-module(q2). -export([main/0, red/1]). red(<<R:8, _G:8, _B:8>>) -> R. main() -> io:format("~p~n", [red(<<10, 20, 30>>)]).Answer
10The first segment binds
Rto the first byte, which is 10. -
What does this module print?
-module(q3). -export([main/0]). main() -> io:format("~p~n", [byte_size(<<8364/utf8>>)]).Answer
3The euro sign takes three bytes in UTF-8, so the binary is three bytes long.
-
What does this module print?
-module(q4). -export([main/0]). main() -> <<Size:16, Rest/binary>> = <<0, 3, 65, 66, 67>>, io:format("~p~n", [{Size, Rest}]).Answer
{3,<<"ABC">>}The size field is 3, and the three payload bytes print as the string ABC, so the tuple is
{3,<<"ABC">>}.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Автор статьи: Arthur Isaev