Skip to content

Core\Math::toBase

Core\Math::toBase writes an int in another base and returns the digits as a string. The base is from 2 to 36. Base 2 is binary, base 16 is hexadecimal, and digits above 9 are the lower case letters a to z.

The result has no prefix such as 0x and no leading zeros. Zero is "0". A negative number starts with -. A base outside 2 to 36 throws a RuntimeError.

Core\Math::fromBase does the opposite. It reads the digits and returns the int.

The examples below show binary and hexadecimal numbers, then which bases are allowed, then how to turn a numeric id into a short code for a link.

Parameters

  • $nintThe number to write. It can be negative.
  • $baseuintThe base, from 2 to 36. Base 2 is binary and base 16 is hexadecimal.

Return value

Returns string. The digits, with no prefix and no leading zeros. A negative $n starts with -. 0 returns "0".

Errors

  • RuntimeErrorWhen $base is outside 2 to 36.

Examples

Binary and hex

<?nvs
// Shows how to write a number in binary, octal and hexadecimal.
// This prints 1010, 12 and a.
echo Core\Math::toBase(10, 2), "\n";
echo Core\Math::toBase(10, 8), "\n";
echo Core\Math::toBase(10, 16), "\n";
// Digits above 9 are lower case letters. This prints ff and zz.
echo Core\Math::toBase(255, 16), "\n";
echo Core\Math::toBase(1295, 36), "\n";
// A negative number starts with `-`. This prints -ff.
echo Core\Math::toBase(-255, 16), "\n";
// Zero is the digit 0 in every base. This prints 0.
echo Core\Math::toBase(0, 2), "\n";
Output
1010
12
a
ff
zz
-ff
0

A base that does not exist

<?nvs
// Shows which bases `Core\Math::toBase` accepts.
// The base must be from 2 to 36. Base 1 and base 37 throw a `RuntimeError`.
array<uint> $bases = [1, 2, 36, 37];
foreach ($bases as uint $base) {
try {
string $digits = Core\Math::toBase(35, $base);
echo 'base ', $base, ': ', $digits, "\n";
} catch (RuntimeError $e) {
echo 'base ', $base, ": not allowed\n";
}
}
Output
base 1: not allowed
base 2: 100011
base 36: z
base 37: not allowed

Short link code

<?nvs
// Shows how to turn a numeric id into a short code for a link, and read the id back.
class ShortLink
{
// Base 36 uses the digits and the letters `a` to `z`, so the code is short.
public static function code(int $id): string
{
return Core\Math::toBase($id, 36);
}
// `Core\Math::fromBase` reads the code and returns the id.
public static function id(string $code): int
{
return Core\Math::fromBase($code, 36);
}
}
// This prints https://example.com/s/2n9c for the id 123456.
string $code = ShortLink::code(123456);
echo 'https://example.com/s/', $code, "\n";
// This prints 123456.
echo ShortLink::id($code), "\n";
Output
https://example.com/s/2n9c
123456