Skip to content

Instantly share code, notes, and snippets.

@gunderwonder
Created August 22, 2010 11:42
Show Gist options
  • Save gunderwonder/543676 to your computer and use it in GitHub Desktop.
Save gunderwonder/543676 to your computer and use it in GitHub Desktop.
Base-encoding/decoding with arbitrary radix.
<?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