You can get the first bytes nusing pattern matching:
iex(1)> n = 4
4
iex(2)> <<head :: binary-size(n)>> <> rest = "my string"
"my string"
iex(3)> head
"my s"
iex(4)> rest
"tring"
You cannot get the first nUTF-8 code points using a single pattern, since UTF-8 characters can occupy a variable number of bytes, and pattern matching does not support Elixir. You can get the first (or a fixed number) of UTF-8 code points using ::utf8in the template:
iex(1)> <<cp::utf8>> <> rest = "ƒoo"
"ƒoo"
iex(2)> cp
402
iex(3)> <<cp::utf8>>
"ƒ"
iex(4)> rest
"oo"
source
share