function Calculator::fromArbitraryBase
Converts a non-negative number in an arbitrary base using a custom alphabet, to base 10.
Parameters
string $number The number to convert, validated as a non-empty string,: containing only chars in the given alphabet/base.
string $alphabet The alphabet that contains every digit, validated as 2 chars minimum.:
int $base The base of the number, validated from 2 to alphabet length.:
Return value
string The number in base 10, following the Calculator conventions.
1 call to Calculator::fromArbitraryBase()
- Calculator::fromBase in vendor/
brick/ math/ src/ Internal/ Calculator.php - Converts a number from an arbitrary base.
File
-
vendor/
brick/ math/ src/ Internal/ Calculator.php, line 363
Class
- Calculator
- Performs basic operations on arbitrary size integers.
Namespace
Brick\Math\InternalCode
public final function fromArbitraryBase(string $number, string $alphabet, int $base) : string {
// remove leading "zeros"
$number = \ltrim($number, $alphabet[0]);
if ($number === '') {
return '0';
}
// optimize for "one"
if ($number === $alphabet[1]) {
return '1';
}
$result = '0';
$power = '1';
$base = (string) $base;
for ($i = \strlen($number) - 1; $i >= 0; $i--) {
$index = \strpos($alphabet, $number[$i]);
if ($index !== 0) {
$result = $this->add($result, $index === 1 ? $power : $this->mul($power, (string) $index));
}
if ($i !== 0) {
$power = $this->mul($power, $base);
}
}
return $result;
}