Search code examples
phpperlfunctionbase32

Convert a Perl function to PHP


I want to convert the perl function below to PHP function, if someone could help a little bit I'd appreaciate it:

sub encode32
{
    $_=shift;
    my($l,$e);
    $_=unpack('B*',$_);
    s/(.....)/000$1/g;
    $l=length;
    if($l & 7)
    {
        $e=substr($_,$l & ~7);
        $_=substr($_,0,$l & ~7);
        $_.="000$e" . '0' x (5-length $e);
    }
    $_=pack('B*', $_);
    tr|\0-\37|A-Z2-7|;
    lc($_);
}

Thanks in advance.


Solution

  • It's a homegrown implementation of the Base32 encoding from RFC 3548. A PHP implementation distributed under the terms of the GPL is available at Fremnet.

    Example use:

    <?
    include('class.base32.php5');
    
    function encode32($str) {
      $b = new Base32(Base32::csRFC3548);
      return strtolower($b->fromString($str));
    }
    
    print encode32("foo bar baz quux") . "\n";
    ?>
    

    Output:

    mzxw6idcmfzcaytbpiqhc5lvpa