Back to Base32 class

Method fromBin

private string
fromBin
(mixed $str)
fromBin
Parameters
  • string $str The string of 0's and 1's you want to convert
Returns
  • string String encoded as base32
-
  • \Exception
Class: Base32
Project: Joomla

Method fromBin - Source code

/**
 * fromBin
 *
 * Converts a correct binary string to base32
 *
 * @param   string  $str  The string of 0's and 1's you want to convert
 *
 * @return  string  String encoded as base32
 *
 * @throws  \Exception
 */
private function fromBin($str)
{
    if (\strlen($str) % 8 > 0) {
        throw new \Exception('Length must be divisible by 8');
    }
    if (!preg_match('/^[01]+$/', $str)) {
        throw new \Exception('Only 0\'s and 1\'s are permitted');
    }
    // Base32 works on the first 5 bits of a byte, so we insert blanks to pad it out
    $str = preg_replace('/(.{5})/', '000$1', $str);
    // We need a string divisible by 5
    $length = \strlen($str);
    $rbits = $length & 7;
    if ($rbits > 0) {
        // Excessive bits need to be padded
        $ebits = substr($str, $length - $rbits);
        $str = substr($str, 0, $length - $rbits);
        $str .= "000{$ebits}" . str_repeat('0', 5 - \strlen($ebits));
    }
    preg_match_all('/.{8}/', $str, $chrs);
    $chrs = array_map(array($this, '_mapcharset'), $chrs[0]);
    return implode('', $chrs);
}