Sheshank Kodam
Sheshank Kodam

Reputation: 515

How to Convert Hexadecimal to Integer in Elixir?

I'm seeing argument error when tried to convert hexadecimal to string using List.to_integer

iex(1)> List.to_integer("C5",16)
** (ArgumentError) argument error
:erlang.list_to_integer("C5", 16)

The same works in erlang

3> list_to_integer("C5", 16).
197

Upvotes: 2

Views: 961

Answers (2)

legoscia
legoscia

Reputation: 41527

In Elixir, characters surrounded by double quotes are strings, not lists, so you need to use String.to_integer instead of List.to_integer:

iex(1)> String.to_integer("C5", 16)
197

Elixir "strings" are the same type as Erlang "binaries":

iex(2)> is_binary("C5")
true

If you use single quotes instead of double quotes, you get what Elixir calls a "charlist" and Erlang calls a "string" - that is, a list of integers corresponding to Unicode codepoints:

iex(3)> is_list('C5')
true
iex(4)> [a, b] = 'C5'
'C5'
iex(5)> a
67
iex(6)> b
53

Upvotes: 3

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Quotes matter.

List.to_integer('C5', 16)
#⇒ 197

In Elixir charlist should be put into single quotes. Double quotes are reserved for binaries.


If you want to convert a binary to integer, one option would be to go through charlist:

"C5" |> to_charlist() |> List.to_integer(16)
#⇒ 197

Another option would be to Integer.parse/2:

with {result, _} <- Integer.parse("C5", 16), do: result
#⇒ 197

Upvotes: 5

Related Questions