Convert hex string to integer

I have a package of hexadecimal values โ€‹โ€‹that I'm trying to handle. They enter a line. For example, one part of the C0 packet, which is equal to 192 . However, I'm not quite sure how to convert the string value to an integer value.

If I use this:

 Base.decode16!("C0") # <<192>> 

... I get a binary file.

The only way I can think to extract this integer value is like this:

 <<x>> = Base.decode16!("C0") x # 192 

It works, and it looks like an idiom, but I'm new to Elixir and don't know how much the best solution is. How could you translate the hex value of a string to an integer in Elixir?

+6
source share
2 answers

You can use integer

 Integer.parse("C0", 16) # returns {192, ""} 

To convert it back, you can use

 # to charlist Integer.to_charlist(192, 16) # returns 'C0' # to string Integer.to_string(192, 16) # returns "C0" 
+11
source

You can convert the binary into an integer, which it represents through :binary.decode_unsigned/1 :

 iex> 192 |> :binary.encode_unsigned |> Base.encode16 "C0" iex> "C0" |> Base.decode16! |> :binary.decode_unsigned 192 
+5
source

All Articles