Arbitrary number base converter.
Easily convert numbers between arbitrary bases and symbol sets.
This library is available on Packagist as thunderer/numbase
. It requires PHP >=7.4
and GMP extension for handling large numbers. For older PHP versions please use ^0.1
constraint which works with 5.3
and above.
The Simplest Way™
use Thunder\Numbase\Numbase;
$numbase = Numbase::createDefault();
// decimal 15 to hexadecimal number
assert('F' === $numbase->convert(15, 10, 16));
// 64000 decimal to base 32000
assert('20' === $numbase->convert(64000, 10, 32000));
Regular usage (see Internals section for more options):
use Thunder\Numbase\Numbase;
$base62 = new Base62Symbols();
$numbase = new Numbase(new GmpConverter($base62), new StrictFormatter($base62));
// decimal 15 to hexadecimal number
assert('F' === $numbase->convert(15, 10, 16));
Showcase
Convert number to and from a different set of symbols:
$base10 = new Base10Symbols();
$upper = new StringSymbols('!@#$%^&*()');
$numbase = new Numbase(new GmpDigits($base10), new StrictFormatter($upper));
assert('#!' === $numbase->convert('20', 10, 10));
assert('-$!' === $numbase->convert('-30', 10, 10));
$numbase = new Numbase(new GmpDigits($upper), new StrictFormatter($base10));
assert('20' === $numbase->convert('#!', 10, 10));
assert('-30' === $numbase->convert('-$!', 10, 10));
Get array of digit values (for bases too large for any symbol set):
$numbase = new Numbase(new GmpDigits(new Base62Symbols()), new ArrayFormatter());
// convert 10^12 to base 99:
assert(array('10', '61', '53', '3', '51', '60', '10')
=== $numbase->convert('10000000000000', 10, 99));
Numbase is built upon several concepts:
There are several implementations of each concept bundled with this library, for example:
gmp_*()
functions,gmp_strval()
to convert between bases 2 and 62,base_convert()
to convert between bases 2 and 32,array(value => symbol)
,0-9A-Za-z up
to base 62,The named constructor Numbase::createDefault()
uses GmpConverter
, StrictFormatter
and Base62Symbols
as defaults.
See LICENSE file in the main directory of this library.