Last active
August 26, 2020 01:16
-
-
Save sunaoka/6362065 to your computer and use it in GitHub Desktop.
10進数を62進数に、62進数を10進数に変換する関数
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 | |
// dec2dohex()、dohex2dec() の $hashtable のは同じものであれば、順序を入れ替えても何ら問題ない。 | |
/** | |
* 10進数を62進数に変換する | |
* | |
* @param int $dec 10進数の値 | |
* | |
* @return string | |
*/ | |
function dec2dohex(int $dec): string | |
{ | |
$hashtable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
$result = ''; | |
while ($dec > 0) { | |
$mod = $dec % 62; | |
$result = $hashtable[$mod] . $result; | |
$dec = ($dec - $mod) / 62; | |
} | |
return $result; | |
} | |
/** | |
* 62進数を10進数に変換する | |
* | |
* @param string $dohex 62進数の値 | |
* | |
* @return int | |
*/ | |
function dohex2dec(string $dohex): int | |
{ | |
$hashtable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; | |
$result = 0; | |
foreach (str_split($dohex) as $string) { | |
$result = $result * 62 + strpos($hashtable, $string); | |
} | |
return $result; | |
} | |
assert(dec2dohex(PHP_INT_MAX) === 'aZl8N0y58M7'); | |
assert(dohex2dec('aZl8N0y58M7') === PHP_INT_MAX); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment