Instantly share code, notes, and snippets.

Embed
What would you like to do?
A base56 implementation
<?php
class Base56
{
/**
* Base56 alphabet. Technically, this component will do arbitrary encoding
* depending upon the alphabet, but whatevs!
* @var string
*/
private static $_alphabet = '23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz';
/**
* The encoded maximum addressible number.
* @var string
*/
private static $_max = 'yqWeWeMYeK9';
/**
* Encodes an integer to a base-56 representation.
* @param integer $number
* @return string
*/
public static function encode($number)
{
$base = strlen(self::$_alphabet);
$data = '';
while($number > 0)
{
$remainder = $number % $base;
$number = (int) (($number - $remainder) / $base);
$data .= self::$_alphabet[$remainder];
}
return strrev($data);
}
/**
* Decodes an integer from its base-56 representation.
* @param string $data
* @return integer
*/
public static function decode($data)
{
// Allow 0 to be used as a padding character for fixed-length representations
$data = str_replace('0', '', $data);
$base = strlen(self::$_alphabet);
$valueMap = array_flip(str_split(self::$_alphabet));
$number = 0;
if(strspn($data, self::$_alphabet) !== strlen($data) || $data > self::$_max)
{
throw new Exception('Invalid Base56 string');
}
$data = strrev($data);
for($i = 0, $j = strlen($data); $i < $j; ++$i)
{
// Retrieves the numeric representation for this character and then
// performs what is effectively a shift
$number += $valueMap[$data[$i]] * pow($base, $i);
}
return $number;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment