Created
June 12, 2012 22:42
-
-
Save simmo/2920592 to your computer and use it in GitHub Desktop.
Base58 Trait (like Base62) Encode/Decode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Base58 Encode/Decode Trait for PHP | |
// ================================== | |
// Base58 is like Base62 except that it removes certain problematic characters such as 0, O, I, and l. | |
// This is great if you need the encoded output to be easily human-readable. Like short URLs... | |
// | |
trait Base58 { | |
private $alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'; | |
function base63_encode($num) { | |
$base_count = strlen($this->alphabet); | |
$encoded = ''; | |
while ($num >= $base_count) { | |
$div = $num / $base_count; | |
$mod = ($num - ($base_count * intval($div))); | |
$encoded = $this->alphabet[$mod] . $encoded; | |
$num = intval($div); | |
} | |
if ($num) $encoded = $this->alphabet[$num] . $encoded; | |
return $encoded; | |
} | |
function base63_decode($num) { | |
$decoded = 0; | |
$multi = 1; | |
while (strlen($num) > 0) { | |
$digit = $num[strlen($num) - 1]; | |
$decoded += $multi * strpos($this->alphabet, $digit); | |
$multi = $multi * strlen($this->alphabet); | |
$num = substr($num, 0, -1); | |
} | |
return $decoded; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment