binaryelixirbitstring

Convert a binary string of 0s and 1s to a bitstring in elixir


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.


Solution

  • 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>>