tuupola / base62

Base62 encoder and decoder for arbitrary data
MIT License
194 stars 19 forks source link

[Suggestion] Add support to encode hex directly #5

Closed ElfSundae closed 6 years ago

ElfSundae commented 6 years ago
$hex = '123456abcdef';
Base62::encode($hex);  // "JngPBzse6O99qumM"
Base62::encode(hex2bin($hex)); // "5gOMRIbf"

I think it is better to add encodeHex and decodeHex methods, then we can encode hex directly like Base62::encodeHex($hex). And for internal, we may call encodeHex for string encoding like:

public function encodeHex($data)
{
    return ctype_xdigit($data) ? gmp_strval(gmp_init($data, 16), 62) : '';
}

public function encode($data, $integer = false)
{
    if (is_integer($data) || true === $integer) {
        return gmp_strval(gmp_init($data, 10), 62);
    }

    return $this->encodeHex(bin2hex($data));
}
tuupola commented 6 years ago

Adding helper functions for different possible encodings is unnecessary. The example you posted is short and concise.

Base62::encode(hex2bin($hex));
ElfSundae commented 6 years ago

Then for hex there are two unnecessary convert ?

https://github.com/tuupola/base62/blob/master/src/Base62/GmpEncoder.php#L36

tuupola commented 6 years ago

That is lesser evil than having convenience method for each numerical system.

ElfSundae commented 6 years ago

OK.