DEV Community 👩‍💻👨‍💻


Posted on

From BitString to Base2 with Elixir

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(" ")

Calling the function defined above like:

"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


originally posted on

Top comments (0)

18 Useful Github Repositories Every Developer Should Bookmark

18 Useful GitHub repositories every developer should bookmark: everything from learning resources and roadmaps to best practices, system designs, and tools.