Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a binary string to Hexadecimal and vice-versa in Elixir

How do you convert a binary string to a Hexadecimal String and vice-versa in Elixir?

There are a few posts on SO regarding this topic for other "main stream" languages. There's even an SO post that benchmarks various C# implementations

How do we do this in elixir?

My implementation was too ugly to share... :(

like image 876
Charles Okwuagwu Avatar asked Oct 26 '15 14:10

Charles Okwuagwu


People also ask

What is a bitstring Elixir?

A bitstring is a fundamental data type in Elixir, denoted with the <<>> syntax. A bitstring is a contiguous sequence of bits in memory.

What is charlist?

A group of one or more characters enclosed by [ ] as part of Like operator's right string expression. This list contains single characters and/or character ranges which describe the characters in the list. A range of characters is indicated with a hyphen (-) between two characters.

How do you convert binary to hex in python?

We use int() and hex() to convert a binary number to its equivalent hexadecimal number.

Can we convert string to hex in python?

To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.


2 Answers

There is Base.encode16/2:

iex(1)> Base.encode16("foo")
"666F6F"

You can also specify the case:

iex(2)> Base.encode16("foo", case: :lower)
"666f6f"
like image 68
Gazler Avatar answered Sep 18 '22 08:09

Gazler


I came here wanting to convert between hex strings and binary data (not strings). The accepted answer is correct, because strings in Elixir are binaries, but I found it confusing that the answer uses "foo" as an example. Base.encode16/2 / Base.decode16!/2 works for all binaries, of which strings are a subset.

Hex to binary:

Base.decode16!("0001FEFF")
=> <<0, 1, 254, 255>>

Binary to hex:

Base.encode16(<<0, 1, 255, 255>>)
=> "0001FFFF"

Base.encode16(<<0x66, 0x6F, 0x6F>>) # equivalent to "foo"
=> "666F6F"

Base.encode16("foo")
=> "666F6F"
like image 44
Adam Millerchip Avatar answered Sep 21 '22 08:09

Adam Millerchip