Web/PHP

base36

aucd29 2013. 9. 26. 21:50
<?php
function dec2string ($decimal, $base)
{
    global $error;
    $string = null;

    $base = (int)$base;
    if ($base < 2 | $base > 36 | $base == 10) {
     echo 'BASE must be in the range 2-9 or 11-36';
     exit;
    } // if;

    $charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charset = substr($charset, 0, $base);

    if (!ereg('(^[0-9]{1,16}$)', trim($decimal))) {
     $error['dec_input'] = 'Value must be a positive integer';
     return false;
    } // if
    $decimal = (int)$decimal;

    do {

     $remainder = ($decimal % $base);

//28
     $char = substr($charset, $remainder, 1);
     $string = "$char$string";

     $decimal = ($decimal - $remainder) / $base;

    } while ($decimal > 0);

    return $string;

} // dec2string


function string2dec ($string, $base)
{
    global $error;
    $decimal = 0;

    $base = (int)$base;
    if ($base < 2 | $base > 36 | $base == 10) {
     echo 'BASE must be in the range 2-9 or 11-36';
     exit;
    } // if;

    $charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charset = substr($charset, 0, $base);

    $string = trim($string);
    if (empty($string) {
     $error[] = 'Input string is empty';
     return false;
    } // if

    do {

     $char = substr($string, 0, 1);
     $string = substr($string, 1);

     $pos = strpos($charset, $char);
     if ($pos === false) {
         $error[] = "Illegal character ($char) in INPUT string";
         return false;
     } // if

     $decimal = ($decimal * $base) + $pos;

    } while($string <> null);

    return $decimal;
    
} // string2dec
?>