Skip to content

Instantly share code, notes, and snippets.

@mattsan
Created June 9, 2019 12:45
Show Gist options
  • Save mattsan/af7b080c2bb3ee19d752202c099346c8 to your computer and use it in GitHub Desktop.
Save mattsan/af7b080c2bb3ee19d752202c099346c8 to your computer and use it in GitHub Desktop.
Elixir の Stream.unfold/2 を使って整数をビット列に分解する例
defmodule Bits do
require Integer
import Integer
import Bitwise
@doc """
A integer value to a bit list.
## example
iex> Bits.to_bits(7)
[1, 1, 1]
iex> Bits.to_bits(10)
[0, 1, 0, 1]
iex> Bits.to_bits(128)
[0, 0, 0, 0, 0, 0, 0, 1]
"""
def to_bits(n) do
n |> Stream.unfold(&bit(&1)) |> Enum.to_list()
end
defp bit(0), do: nil
defp bit(n) when is_odd(n), do: {1, n >>> 1}
defp bit(n), do: {0, n >>> 1}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment