Non tiene conto delle tipologie. Appena testato, non ottimizzato.
Codice PHP:
<?php
class baseX {
//===== Trova la posizione della lettera
private function charPosition($code) {
$len = strlen($code);
$ind = 0;
$pos = -1;
while ($ind < $len) {
if (!is_numeric(substr($code,$ind,1))) {
$pos = $ind;
}
$ind++;
} // while ($ind < $len)
if ($pos == -1) {
return null;
} else {
return $pos;
} // if ($pos == -1)
} // function decodeX($code)
//===== decodifica un numero codificato in base 10
function decodeBaseX($code) {
$pos = $this->charPosition($code);
if ( $pos === null) {
return null;
} // if ($this->charPosition($code) === null)
$letter = substr($code,$pos,1);
$resto = str_replace($letter,'',$code);
$th = ord($letter) - 65;
return ($th * 4000) + ($pos * 1000) + $resto;
} // function decodeBaseX($code)
//===== codifica un numero in base 10
function codeBaseX($number) {
if ($this->charPosition($number) !== null) {
return null;
} // if ($this->charPosition($number) !== null)
$th = (int) ($number / 1000);
$resto = $number - ($th * 1000);
$restoF = str_repeat('0',3-strlen($resto)).$resto;
$tx = (int) ($th / 4);
$pos = $th % 4;
$letter = chr(65+$tx);
if ($pos == 0) {
$return = $letter.$restoF;
} else {
if ($pos == 1) {
$return = substr($restoF,0,1).$letter.substr($restoF,1,2);
} else {
if ($pos == 2) {
$return = substr($restoF,0,2).$letter.substr($restoF,2,1);
} else {
$return = $restoF.$letter;
} // if ($pos == 2)
} // if ($pos == 1)
} // if ($pos == 0)
return $return;
} // function codeBaseX($number)
//===== aggiunge due "numeri"
function add($element1,$element2) {
if ($this->charPosition($element1) === null) {
$add_element1 = $element1;
} else {
$add_element1 = $this->decodeBaseX($element1);
} // if (charPosition($element1) === null)
if ($this->charPosition($element2) === null) {
$add_element2 = $element2;
} else {
$add_element2 = $this->decodeBaseX($element2);
} // if (charPosition($element2) === null)
$inter = $add_element1 + $add_element2;
//PRINT $inter;
return $this->codeBaseX($inter);
} // function add($element1,$element2)
} // class baseX
$a = new baseX();
print "Code :<br/>";
print $a->codeBaseX(15)."<br/>";
print $a->codeBaseX(999)."<br/>";
print $a->codeBaseX(3400)."<br/>";
print $a->codeBaseX(1999)."<br/>";
print $a->codeBaseX(2000)."<br/>";
print $a->codeBaseX(3000)."<br/>";
print $a->codeBaseX(4000)."<br/>";
print $a->codeBaseX(5000)."<br/>";
print "Decode :<br/>";
print $a->decodeBaseX('4D00')."<br/>";
print $a->decodeBaseX('8P99')."<br/>";
print "Add :<br/>";
for ($i=0;$i<100;$i++) {
print $a->add('9D50',$i)."<br/>";
} // for ($i=0;$i<100;$i++)
print $a->codeBaseX(17128)."<br/>";
print $a->decodeBaseX('25I6')."<br/>";
print $a->add('1E28','1E28');
?>