Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hexadecimal string to integer

Tags:

elixir

I have a packet of hexadecimal values that I'm trying to deal with. They come in as a string. For example, one piece of the packet is C0, which is 192. However, I'm not quite sure how to translate the string value into the integer value.

If I use this:

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

... I get a binary.

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

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

This works, and it seems sort of idiomatic, but I'm new to Elixir and bit unsure if this is the best solution. How would you go about translating a string hex value into an integer in Elixir?

like image 501
Elliot Larson Avatar asked Dec 21 '15 21:12

Elliot Larson


1 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"
like image 100
Dmitry Biletskyy Avatar answered Sep 28 '22 06:09

Dmitry Biletskyy