Skip to content

Instantly share code, notes, and snippets.

@sunaoka
Last active August 26, 2020 01:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunaoka/6362065 to your computer and use it in GitHub Desktop.
Save sunaoka/6362065 to your computer and use it in GitHub Desktop.
10進数を62進数に、62進数を10進数に変換する関数
<?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