Current section
Files
Jump to
Current section
Files
lib/elixir/integer.ex
defmodule AntlUtils.Elixir.Integer do
@alphabets %{
62 => "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
64 => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
}
@doc """
Returns a binary which corresponds to the text representation of integer in the given base
base can be an integer between 2 and 36, 62 or 64
## Examples
iex> Integer.to_string(0, 62)
"0"
iex> Integer.to_string(1, 62)
"1"
"""
@spec to_string(integer, 1..255) :: binary
def to_string(integer, base)
when is_integer(integer) and is_integer(base) and base >= 2 and base <= 32 do
Integer.to_string(integer, base)
end
def to_string(integer, base) when is_integer(integer) and base in [62, 64] do
to_string(integer, "", base)
end
defp to_string(integer, "", _base) when is_integer(integer) and integer <= 0 do
"0"
end
defp to_string(integer, acc, _base) when is_integer(integer) and integer <= 0 do
acc
end
defp to_string(integer, acc, base)
when is_number(integer) and integer > 0 and is_binary(acc) and is_integer(base) do
remainder = rem(integer, base)
to_string(
div(integer - remainder, base),
"#{String.at(Map.get(@alphabets, base), remainder)}#{acc}",
base
)
end
end