Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a Unicode code point into a Unicode String?

I have a string representing a Unicode code point, like "272d". How do I turn that into "✭"?

Elixir certainly understands Unicode:

iex> << 10029 :: utf8 >>
"✭"

iex> "x{272d}"
"✭"

But I need a function that takes in four characters and returns the Unicode String:

def from_code_point(<< code_point :: size(32) >>) do
  ???
end

or possibly

def from_code_point(<< a, b, c, d >>) do
  ???
end

I also tried this as a macro:

defmacro from_code_point(<< code_point :: size(32) >>) do
  quote do
    "x{unquote(code_point)}"
  end
end

But that just returns "x{unquote(code_point)}".

like image 621
James A. Rosen Avatar asked Aug 07 '26 18:08

James A. Rosen


1 Answers

A Unicode codepoint is a number, so the first thing you need to do is parse your string to see what value it represents. You can use binary_to_integer/2 (available in R16, for R15 you'd need to go through binary_to_list/1 and then list_to_integer/2.

Once you have the numerical value of the codepoint, you can simply plonk it in a binary (which is the underlying representation of a string) by telling elixir that the number you're passing is an Unicode codepoint, like so

def to_string(input) do
  <<binary_to_integer(input, 16) :: utf8>>
end

if you have to extract it out of a larger string, the you can put String.slice/3 in between like so

def to_string2(input) do
  codepoint = String.slice(input, 0, 4)
  <<binary_to_integer(codepoint, 16) :: utf8>>
end
like image 196
Carlos Martín Nieto Avatar answered Aug 10 '26 08:08

Carlos Martín Nieto