Created
August 22, 2010 11:42
-
-
Save gunderwonder/543676 to your computer and use it in GitHub Desktop.
Base-encoding/decoding with arbitrary radix.
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
<?php | |
/** | |
* Base-encoding/decoding with arbitrary radix. | |
* @see http://stackoverflow.com/questions/1119722/base-62-conversion-in-python#answer-1119769 | |
*/ | |
define('BASE_64_ALPHABET', '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); | |
function xbase_encode($number, $alphabet = BASE_64_ALPHABET) { | |
if ($number == 0) | |
return $alphabet[0]; | |
else if ($number < 0) | |
$number = abs($number); | |
$encoded = ''; | |
$base = strlen($alphabet); | |
while ($number) { | |
$reminder = $number % $base; | |
$number = floor(($number - $reminder) / $base); | |
$encoded .= $alphabet[$reminder]; | |
} | |
return strrev($encoded); | |
} | |
function xbase_decode($string, $alphabet = BASE_64_ALPHABET) { | |
$base = strlen($alphabet); | |
$length = strlen($string); | |
$decoded = 0; | |
for ($split = str_split($string), $i = 0; $i < count($split); $i++) | |
$decoded += strpos($alphabet, $split[$i]) * pow($base, $length - $i - 1); | |
return $decoded; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment