Search code examples
phpbase-conversion

Reverse custom base encode in PHP


I have a program that encodes integers into random looking, unique, maxiumum 5 character strings using a custom base array. I'd like to decode that string back to an integer. Not sure how to accomplish that.

Code:

function intToAlphaBaseN($n, $baseArray) {
 $l=count($baseArray);
 $s = '';
 for ($i = 1; $n >= 0 && $i < 6; $i++) {
  $s =  $baseArray[($n % pow($l, $i) / pow($l, $i - 1))].$s;
  $n -= pow($l, $i);
 }
 return $s;
}

$alpha=array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '2', '3', '4', '5', '6', '7', '8', '9');
$number = 1234;
echo("Number: " . $number . " Converted: " . intToAlphaBaseN($number, $alpha)); 

Output: Number: 1234 Converted: afu

Would like to be able to decode something like "afu".


Solution

  • No, you can't decode string into number, because you don't know last value of $n in function.

    For example, last array index is 0 ('a') and $i=strlen('afu');.

    0=$n % pow($l, $i) / pow($l, $i - 1)

    0=$n % 39304 / 1156

    $n=[0,1155]+39304*c; where c=0,1,2,3... and $n is the last value of $n in cycle.

    When you find last $n value, you can find full $number by summing pow($l, $i) in decrease cycle.

    This full $n place between pow($l, 1) + pow($l, 2) and pow($l, 1) + pow($l, 2) + pow($l, 3).