Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Hexadecimal to Integer in Elixir?

Tags:

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
like image 864
Sheshank Kodam Avatar asked Nov 17 '25 18:11

Sheshank Kodam


1 Answers

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
like image 119
Aleksei Matiushkin Avatar answered Nov 19 '25 08:11

Aleksei Matiushkin