2

Given a string such as "0110", how do I convert this to a bitstring containing the binary values represented by the string?

I checked the Base module, but it's based on RFC 4648 and is not designed for handling Base 2.

1 Answer 1

3

Here's one way:

defmodule Convert do
  def to_bitstring(str) when is_binary(str) do
    for <<byte::binary-1 <- str>>, into: <<>> do
      case byte do
        "0" -> <<0::1>>
        "1" -> <<1::1>>
      end
    end
  end
end

Usage:

iex> Convert.to_bitstring("0110")
<<6::size(4)>>

The benefit of doing it exhaustively using case and matching on binaries is two-fold:

  1. The function will reject invalid characters
  2. The error message in the above case is easy to understand:
iex> Convert.to_bitstring("0140")
** (CaseClauseError) no case clause matching: "4"

If you just want a quick hack, this works, but it will also happily convert nonsense like "0140" too, so I think the first solution is better.

for <<byte <- str>>, into: <<>>, do: <<(byte - ?0)::1>>
Sign up to request clarification or add additional context in comments.

4 Comments

for <<byte <- str>>, (byte in [?0, ?1] || raise "boom"), …
Or keep the case but match on ?0 and ?1
@sabiwara sure but then you lose the point 2) above and get errors like ** (CaseClauseError) no case clause matching: 52
Oh you're right. I missed that, nice!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.