Convertat

Provides functions for converting from and to arbitrary bases.

Source

Summary

from_base(digits, base)

Converts any string of digits or list of digits (where each digit is a string) to a value in decimal base (base 10), given a starting base

to_base(val, base, opts \\ [as_list: false])

Converts a value in decimal base (val, which has to be an integer) to an arbitrary base. If the :as_list option is true, the resulting value in base base will be returned as a list of digits instead of a string of digits

Types

integer_base :: 2 .. 36

list_base :: []

Functions

from_base(digits, base)

Specs:

Converts any string of digits or list of digits (where each digit is a string) to a value in decimal base (base 10), given a starting base.

The starting base can be an integer in the 2..36 range (in which case the native String.to_integer/2 function is used) or a list with at least two elements (digits).

Examples

iex> "101" |> Convertat.from_base(2)
5

iex> "fe" |> Convertat.from_base(16)
254

iex> "foo" |> Convertat.from_base(["f", "o"])
3

iex> "↑" |> Convertat.from_base(["↓", "↑"])
1

iex> ["foo", "bar"] |> Convertat.from_base(["bar", "foo"])
2

iex> "test" |> Convertat.from_base(["onedigit"])
** (ArgumentError) list bases must have at least two digits
Source
to_base(val, base, opts \\ [as_list: false])

Specs:

Converts a value in decimal base (val, which has to be an integer) to an arbitrary base. If the :as_list option is true, the resulting value in base base will be returned as a list of digits instead of a string of digits.

Examples

iex> 35 |> Convertat.to_base(36)
"z"

iex> 11 |> Convertat.to_base(["a", "b"])
"babb"

iex> 6 |> Convertat.to_base(["foo", "bar"], as_list: true)
["bar", "bar", "foo"]

iex> 10 |> Convertat.to_base(["↓", "↑"])
"↑↓↑↓"

iex> 42 |> Convertat.to_base(["onedigitbase"])
** (ArgumentError) list bases must have at least two digits
Source