Current section
Files
Jump to
Current section
Files
lib/gray.ex
defmodule Gray do
@moduledoc """
This module helps you convert non_neq_integers to binary reflected gray code
and vice versa
"""
use Bitwise
# import Gray.Utils, only: [to_binary: 1]
@doc """
Converts a non negative integer to its binary reflected gray code equivalent
"""
def binary_to_gray(num) when is_integer(num) and num >= 0 do
(num >>> 1) ^^^ num
end
@doc """
Converts a binary reflected gray code number to its original decimal form
"""
def gray_to_binary(num) when is_integer(num) and num >= 0 do
gray_to_binary(num, num >>> 1)
end
# Recursive way to convert BRGC code to decimal form
defp gray_to_binary(num, 0), do: num
defp gray_to_binary(num, mask) do
gray_to_binary(num ^^^ mask, mask >>> 1)
end
end