DEV Community

Tiemen
Tiemen

Posted on

2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay