DEV Community

loading...

From BitString to Base2 with Elixir

tiemen profile image Tiemen ・1 min read

If you ever worked with the BitString type in Elixir you're probably familiar with the <<104, 101, 108, 108, 111>>-like notation. This is basically a compact notation of printing each byte as their decimal notation. Converting them to a string of ones and zeroes is as easy as combining a BitString generator with some functions from the Enum module, and voila:

defmodule Bits do
  def as_string(binary) do
    for(<<x::size(1) <- binary>>, do: "#{x}")
    |> Enum.chunk_every(8)
    |> Enum.join(" ")
  end
end

Calling the function defined above like:

Bits.as_string("Hello, dev.to")
"01001000 01100101 01101100 01101100 01101111 00101100 00100000 01100100 01100101 01110110 00101110 01110100 01101111"

Where every 8 bits are separated with a space for readability, we can clearly see the patterns of the ASCII table, where:

H = 0100 1000
e = 0110 0101
l = 0110 1100
etc.

🙌

originally posted on https://tiemenwaterreus.com/posts/from-bitstring-to-base2-elixir/

Discussion

pic
Editor guide