Converting to ASCII

Hello,

I haven’t been able to find documentation on converting characters/a string’s characters to ascii. I found that the ? mark works in the iex terminal, but not in code.

I tried this with no luck:

def words_to_marks(s) do
    s
    |> String.graphemes()
    |> Enum.map(fn x -> ?x end)
  end```

Any help would be very appreciated. Thank you.

Erlang :binary.first() will convert to ascii

def to_ascii(string) when is_binary(string) do
  :binary.first(string)
end
1 Like

Hello and welcome,

There is a simple solution… to_charlist()

?a works, but ?“a” will not, so ?x will not work.

iex> "Hello" |> to_charlist() |> IO.inspect(charlists: :as_lists)
[72, 101, 108, 108, 111]
iex> "你好" |> to_charlist() |> IO.inspect(charlists: :as_lists) 
[20320, 22909]

charlist are list of codepoints

3 Likes

Thank you!

? does not give you anything ASCII related, it is a different form to write an integer, and it works in iex and in code, but it does not work with variables. The compiler sees ?x and sees it as the integer representing the unicode code point of Latin Small Letter X, which is 120. Coincidentally this is indeed the same as the ASCII-code for the lower case x.

Also the ways shown here won’t work for any codepoint greater than 127, as those get encoded differently in the binary, anyway, ASCII has only 7 bit and therefore no ASCII code beyond 127 exists, but you should be aware of that.

1 Like