Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting bitstring to string in Elixir

Tags:

elixir

I'm just new to Elixir.

After generating a hmac hash, I got a bitstring:

:crypto.hmac(:sha512, secret, data)
Sign: <<104, 155, 224, 193, 121, 129, 237, 103, 233, 236, 161, 130...>>

Now, I have to convert it to String, but don't know how exactly.

Any Elixir/erlang module to do this directly?

like image 803
Alexandre S Hostert Avatar asked Feb 14 '16 21:02

Alexandre S Hostert


People also ask

How do you convert int to string in Elixir?

String s=((Integer)i). toString(); Demo.

Is bitstring Elixir?

A bitstring is a fundamental data type in Elixir, denoted with the <<>> syntax.

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.


1 Answers

Oops, I didn't see that you originally want to use the output of the bitstring with the String Module. You already can! You can see this by trying to pipe your output into String.length and getting a successful return value.

This getting started guide does a good job of walking through the basics. Specifically how "A string is a UTF-8 encoded binary".

What do you want to be able to do with the output?

If you you instead want to be able to pass the hash through URL for an auth system or something like that, I left the original answer.


You can use the Base Module to achieve that.

For example you could pipe the output like

:crypto.hmac(:sha512, secret, data) |> Base.encode64

If you need it to be filename or url safe there is an alternative url_encode64 function.

like image 136
The Brofessor Avatar answered Nov 15 '22 09:11

The Brofessor