Erlang basics · Lesson 12 (open contents)
Build and inspect UTF-8 binaries
Compare code points, bytes, Unicode conversion, and bit-syntax segments.
Run this first
Run it once, change one input, and compare the new result.
%% Inspect Unicode as code points and bytes
Text = unicode:characters_to_binary([16#957F, 16#5B89, 16#1F642]),
<<First/utf8, Rest/binary>> = Text,
{First, byte_size(Text), Rest}.Firstis code point16#957F; the full binary uses 10 bytes.
Read from the first line down
- Read
<<Head/utf8, Rest/binary>>: Read one UTF-8 code point and keep the remaining bytes. - Read
byte_size/1: Count bytes in a binary. - Read
unicode:characters_to_binary/1: Convert character data to UTF-8 bytes.
Symbols are not secret signs
<<Head/utf8, Rest/binary>>Read one UTF-8 code point and keep the remaining bytes.
byte_size/1Count bytes in a binary.
unicode:characters_to_binary/1Convert character data to UTF-8 bytes.
Match each name to its meaning
bit syntax
<<>> builds binaries from integer, binary, and typed segments.
UTF-8 segment
Codepoint/utf8 encodes one Unicode code point into its UTF-8 bytes.
Unicode conversion
unicode:characters_to_binary/1 converts supported character data into a UTF-8 binary.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
<<>> builds binaries from integer, binary, and typed segments.
Codepoint/utf8 encodes one Unicode code point into its UTF-8 bytes.
Close the answer and try
Build the UTF-8 binary for A🙂 and read its first code point.
Text = unicode:characters_to_binary([$A, 16#1F642]),
<<First/____, Rest/____>> = Text,
{First, Rest}.Target result: Use utf8 and binary; First should be 65.
Stuck? Read one hint
The first segment is one code point, the rest is bytes.
After you run it, see one answer
Text = unicode:characters_to_binary([$A, 16#1F642]),
<<First/utf8, Rest/binary>> = Text,
{First, Rest}.Think about it: Is byte count the same as visible-character count?
No. A UTF-8 code point can occupy several bytes, and graphemes can use several code points.
Remember these three lines
- 1
Use binaries for modern text boundaries.
- 2
State UTF-8 in bit syntax.
- 3
Measure bytes only when bytes are the real unit.