Created
June 8, 2012 03:46
-
-
Save wokamoto/2893427 to your computer and use it in GitHub Desktop.
62進数生成
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
<?php | |
function dec_to_n( $dec, $n = 62, $disits = null ) { | |
if ( !$disits ) { | |
$disits = array( | |
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', | |
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', | |
'u', 'v', 'w', 'x', 'y', 'z', | |
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', | |
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', | |
'U', 'V', 'W', 'X', 'Y', 'Z', | |
); | |
} | |
$max_n = count($disits); | |
if ( ! (preg_match('/^\d+$/', $n) && $n >= 2 && $n <= $max_n) ) return FALSE; | |
if ( ! preg_match('/^\d+$/', $dec) ) return FALSE; | |
if ( $dec == 0 ) return $dec; | |
$num_str = ''; | |
while ( $dec !== 0 ) { | |
$num_str = $disits[$dec % $n] . $num_str; | |
$dec = (int) ($dec / $n); | |
} | |
return $num_str; | |
} | |
function n_to_dec( $num_str, $n = 62, $disits = null ) { | |
if ( !$disits ) { | |
$disits = array( | |
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', | |
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', | |
'u', 'v', 'w', 'x', 'y', 'z', | |
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', | |
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', | |
'U', 'V', 'W', 'X', 'Y', 'Z', | |
); | |
} | |
$max_n = count($disits); | |
$valids = array(); | |
for ( $i = 0; $i < $max_n; $i++ ) { | |
$valids[$disits[$i]] = $i; | |
} | |
if ( ! (preg_match('/^\d+$/', $n) && $n >= 2 && $n <= $max_n) ) return FALSE; | |
if ( ! preg_match('/^[\da-zA-Z]+$/', $num_str) ) return FALSE; | |
$dec = 0; | |
for ( $i = 0; $i < strlen($num_str); $i++ ) { | |
$dec += $valids[ substr($num_str, ($i + 1) * -1, 1) ] * pow( $n, $i ); | |
} | |
return $dec; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment