brightDot
brightDot

Reputation: 339

Binary and Unicode string

I have code like this to construct a Binary String

[<<"Hello, ", Name/binary>>]

Trying to read the Name as Unicode. Like this,

[<<"Hello, ", Name/utf16/binary>>]

Looks like it is an obvious wrong syntax. How can I make this work? Thanks in advance.

Upvotes: 0

Views: 659

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170713

Just use /binary and functions from unicode module to convert between encodings.

Your question says first that you are constructing the string, then reading it. If constructing, you could write

Utf16Name = unicode:characters_to_binary(Name, utf8, utf16),
[<<"Hello, ", Utf16Name/binary>>]

EDIT: Except of course, that's bad: "Hello, " will be UTF8! It should be

unicode:characters_to_binary(<<"Hello, ", Name/binary>>, utf8, utf16)

or even

unicode:characters_to_binary(["Hello, ", Name], utf8, utf16)

Upvotes: 1

Related Questions