0
0

[PHP] 可読性0の短めなbase64エンコード・デコード関数 (v2)

Last updated at Posted at 2024-09-07

この記事は、以下の記事に書いたやつがさすがにゴミだったので、その改訂版です

b64fn.php
    $b64Arr = array_merge(range("A", "Z"), range("a", "z"), range("0", "9"), ["+", "/"]);

    function b64safe(string $b64, bool $dec = false, array $rep = [["+", "/", "="], [".", "_", "-"]]):string {
        return str_replace($rep[(int) $dec], $rep[(int) !$dec], $b64);
    }

    function blockPad(string $str, string $pad, int $len, bool|int $right = false) {
        $i = 0;
        while ($i < strlen($str)) $i += $len;
        return str_pad($str, $i, $pad, (int) $right);
    }

    function bin2b64(string $bin):string {
        return blockPad(implode("", array_map(fn($v) => $GLOBALS["b64Arr"][bindec($v)], str_split(blockPad($bin, "0", 6), 6))), "=", 4, true);
    }

    function b642bin(string $b64):string {
        return implode("", array_map(fn($v) => str_pad(decbin(array_search($v, $GLOBALS["b64Arr"], true)), 6, "0", 0), str_split(str_replace("=", "", $b64))));
    }

    function b642intArr(string $b64, int $spl = 5):array {
        return array_map(fn($el) => intval(b642bin($el), 2), str_split(blockPad($b64, "A", $spl), $spl));
    }
関数 引数 引数の説明 返り値
b64safe() $b64 入力するbase64 $repのルールによって
エンコード/デコードされたbase64
$dec false エンコード
true デコード
$rep 変換ルールの指定
blockPad() $str 入力する文字列 $lenの倍数の長さになるように
paddingされた文字列
$pad padに使用する文字
$len pad後の文字列の倍長
$right paddingする方向
bin2b64() $bin 入力するbinary_string $binからbase64へ変換した文字列
bin2b64() $b64 入力するbase64 $b64からbinaryへ変換した文字列
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0