Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: Convert integer to unicode character

I want to iterate over the set of Chinese characters in Elixir given by Unicode. I read the documentation and it says I can use the '?' operator to get the codepoint as an integer and then can increment it. Now I just need to do the inverse, from codepoint to integer. Is there an easy way to do that? I did not find any. For instance, in Python you would do

>>> chr(ord("一") + 1)
    '丁'
like image 803
jcklie Avatar asked Dec 24 '16 14:12

jcklie


1 Answers

There is no character data type in Elixir, but to convert a codepoint to a string containing that character (encoded as UTF-8), you can use either <<x::utf8>> or List.to_string([x]):

iex(1)> x = ?一 + 1
19969
iex(2)> <<x::utf8>>
"丁"
iex(3)> List.to_string([x])
"丁"
like image 137
Dogbert Avatar answered Oct 18 '22 21:10

Dogbert