欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将10进制整数转为64进制形式的PHP实现

程序员文章站 2024-03-17 21:56:16
...
/**
 * @param int $integer 10进制正整数
 * @return string 64进制形式
 */
function decimal_to_base64($integer)
{
    $chars_map = [
        0  => '0',
        1  => '1',
        2  => '2',
        3  => '3',
        4  => '4',
        5  => '5',
        6  => '6',
        7  => '7',
        8  => '8',
        9  => '9',
        10 => 'a',
        11 => 'b',
        12 => 'c',
        13 => 'd',
        14 => 'e',
        15 => 'f',
        16 => 'g',
        17 => 'h',
        18 => 'i',
        19 => 'j',
        20 => 'k',
        21 => 'l',
        22 => 'm',
        23 => 'n',
        24 => 'o',
        25 => 'p',
        26 => 'q',
        27 => 'r',
        28 => 's',
        29 => 't',
        30 => 'u',
        31 => 'v',
        32 => 'w',
        33 => 'x',
        34 => 'y',
        35 => 'z',
        36 => 'A',
        37 => 'B',
        38 => 'C',
        39 => 'D',
        40 => 'E',
        41 => 'F',
        42 => 'G',
        43 => 'H',
        44 => 'I',
        45 => 'J',
        46 => 'K',
        47 => 'L',
        48 => 'M',
        49 => 'N',
        50 => 'O',
        51 => 'P',
        52 => 'Q',
        53 => 'R',
        54 => 'S',
        55 => 'T',
        56 => 'U',
        57 => 'V',
        58 => 'W',
        59 => 'X',
        60 => 'Y',
        61 => 'Z',
        62 => '_',
        63 => '$',
    ];
    $dividend = count($chars_map);

    $base64_chars = [];
    while ($integer > 0) {
        $r = $integer % $dividend;
        $integer = ($integer - $r) / $dividend;
        $base64_chars[] = $chars_map[ $r ];
    }

    return join('', array_reverse($base64_chars));
}