理系学生日記

おまえはいつまで学生気分なのか

Base64 (decode) の PurePerl 実装

encode があって decode がないのはクソみたいだなってことでしたのでつくった.

sub base64_decode {
    my $encoded = shift;
    my @chars = map { ord } split //, $encoded;

    my $ans;
    while( my @group4 = splice @chars, 0, 4 ) {
        no warnings 'uninitialized';

        @group4 = map { ($_ eq '=')? 0 : $_ } @group4;
        $ans .= chr( ($group4[0] << 2) | ($group4[1] & 0x30) >> 4 );
        $ans .= chr( ($group4[1] & 0x0f) << 4 | ($group4[2] & 0x3c) >> 2 );
        $ans .= chr( ($group4[2] & 0x03) << 6 | ($group4[3] & 0x3f) );
    }

    $ans;
}