Get ascii value of a character

Student & New to elixir. Nice language.
I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s ascii value, but I can’t find the function (I found similiar one for << 255 :: utf8 >> but didn’t work for ascii value)
and syntax like ?a didn’t work for variable.
Appreciated for you help!

2 Likes

?a gives you the Unicode codepoint of a as an integer, the first 128 (0 to 127) codepoints are equivalent to US-ASCII.

So I’m not sure what your problem is.

Here’s two ways to do it:

iex(9)> var = "a"
"a"
iex(10)> <<v::utf8>> = var
"a"
iex(11)> v
97
iex(12)> var |> String.to_charlist |> hd
97
13 Likes

Thank you!!!
That’s a very nice solution involving pattern matching!
Didn’t see that coming

If you are certain you are working with ASCII (ie single byte code points) then you can also:

iex> :binary.first "abcdef"
97

But @gregvaughn’s approach would be preferred since it will work with any UTF-8 string.

5 Likes