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

2

21

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... :(

Swop answered 26/10, 2015 at 14:12 Comment(1)
Even though it's not proper conversion, if the goal is only to take a look at the values in binary form, not to process them further, inspect("test", base: :hex) == "<<0x74, 0x65, 0x73, 0x74>>" is also a great option!Cavazos
A
17

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"
Alius answered 23/9, 2020 at 2:46 Comment(0)
P
28

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"
Papism answered 26/10, 2015 at 14:13 Comment(0)
A
17

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"
Alius answered 23/9, 2020 at 2:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.