Home

Awesome

Numbase

Build License Version Psalm

Easily convert numbers between arbitrary bases and symbol sets.

Installation

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.

Usage

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));

Internals

Numbase is built upon several concepts:

There are several implementations of each concept bundled with this library, for example:

The named constructor Numbase::createDefault() uses GmpConverter, StrictFormatter and Base62Symbols as defaults.

License

See LICENSE file in the main directory of this library.