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:
1defmodule Bits do
2 def as_string(binary) do
3 for(<<x::size(1) <- binary>>, do: "#{x}")
4 |> Enum.chunk_every(8)
5 |> Enum.join(" ")
6 end
7end
Calling the function defined above like:
1Bits.as_string("Hello, world!")
2"01001000 01100101 01101100 01101100 01101111 00101100 00100000 01110111 01101111 01110010 01101100 01100100 00100001"
Where every 8 bits are separated with a space for readability, we can clearly see the patterns of the ASCII table, where:
1H = 0100 1000
2e = 0110 0101
3l = 0110 1100
4etc.
🙌