Skip to content

Instantly share code, notes, and snippets.

@jrdnull
Created December 3, 2014 17:59
Show Gist options
  • Save jrdnull/701f35ce06ac407e6b8c to your computer and use it in GitHub Desktop.
Save jrdnull/701f35ce06ac407e6b8c to your computer and use it in GitHub Desktop.
defmodule Base58 do
@alphabet ~c(123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz)
def encode(x), do: _encode(x, [])
def decode(str), do: _decode(str |> to_char_list, 0)
defp _encode(0, acc), do: acc |> to_string
defp _encode(x, acc) do
_encode(div(x, 58), [Enum.at(@alphabet, rem(x, 58)) | acc])
end
defp _decode([], acc), do: acc
defp _decode([c | cs], acc) do
_decode(cs, (acc * 58) + Enum.find_index(@alphabet, &(&1 == c)))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment