Alexandre S Hostert
Alexandre S Hostert

Reputation: 340

Converting bitstring to string in 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?

Upvotes: 7

Views: 6933

Answers (1)

The Brofessor
The Brofessor

Reputation: 2411

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.

Upvotes: 7

Related Questions