Build and inspect UTF-8 binaries: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Compare code points, bytes, Unicode conversion, and bit-syntax segments.
Build 长安🙂 as UTF-8, count its bytes, and extract the first Unicode code point.
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}.First is code point 16#957F; the full binary uses 10 bytes.
Steps for the full example
- 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.
Original lesson notes
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.
Symbols and terms
<<Head/utf8, Rest/binary>>- Read one UTF-8 code point and keep the remaining bytes.
byte_size/1- Count bytes in a binary.
unicode:characters_to_binary/1- Convert character data to UTF-8 bytes.
- bit syntax
<<>>builds binaries from integer, binary, and typed segments.- UTF-8 segment
Codepoint/utf8encodes one Unicode code point into its UTF-8 bytes.- Unicode conversion
unicode:characters_to_binary/1converts supported character data into a UTF-8 binary.
Original full exercise
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}.Use utf8 and binary; First should be 65.
Show hint
The first segment is one code point, the rest is bytes.
Show original answer
Text = unicode:characters_to_binary([$A, 16#1F642]),
<<First/utf8, Rest/binary>> = Text,
{First, Rest}.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.
Original lesson takeaways
- Use binaries for modern text boundaries.
- State UTF-8 in bit syntax.
- Measure bytes only when bytes are the real unit.