Created
January 6, 2016 13:03
-
-
Save Avakulenko/6d987acf7c73432bbcd5 to your computer and use it in GitHub Desktop.
This file contains 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
function crb_encode_short_ref_code($id) { | |
// if (!is_int($id)) { | |
// echo 'not an int'; | |
// } | |
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; | |
if ($id == 0) { | |
return $chars[0]; | |
} | |
$number = abs($id); | |
if ($id < 0) { | |
echo "Can not encode for negative integers"; | |
} | |
$string = ''; | |
$base = strlen($chars); | |
while ($number > 0) { | |
$string .= $chars[$number % $base]; | |
$number = (int) ($number / $base); | |
} | |
return strrev($string); | |
} | |
function crb_decode_short_ref_code($string) { | |
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; | |
$stringLength = strlen($string); | |
$baseLength = strlen($chars); | |
$id = 0; | |
for($i = 0; $i < $stringLength; $i++) { | |
$pos = strpos($chars, $string[$i]); | |
$id = ($id * $baseLength) + $pos; | |
} | |
return $id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment