note 105062 deleted from function.base-convert by danbrown
| From: | danbrown@php.net | Date: | Tue, 26 Jul 2011 16:14:17 +0000 |
| Subject: | note 105062 deleted from function.base-convert by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-181896@lists.php.net to get a copy of this message | ||
Note Submitter: easoft at gmail dot com
----
Somewhat more efficient version of base32 encode/decode, using bitwise operations.
class StringEncoding
{
private static $base32 = array('A', 'B', 'C', 'D',
'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X',
'Y', 'Z', '2', '3', '4', '5',
'6', '7');
private static $base32i = array(
'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3,
'E' => 4, 'F' => 5, 'G' => 6, 'H' => 7,
'I' => 8, 'J' => 9, 'K' => 10, 'L' =>
11, 'M' => 12, 'N' => 13, 'O' => 14, 'P' => 15,
'Q' => 16, 'R' => 17, 'S' => 18, 'T' =>
19, 'U' => 20, 'V' => 21, 'W' => 22, 'X' => 23,
'Y' => 24, 'Z' => 25, '2' => 26, '3' =>
27, '4' => 28, '5' => 29, '6' => 30, '7' => 31
);
public static function encode32($input)
{
$input = strval($input);
$bytes = 0;
$out_last = NULL;
$output = "";
while (isset($input{$bytes}))
{
$byte = ord($input{$bytes});
switch ($bytes % 5)
{
case 0:
$output .= self::$base32[($byte & 248) >> 3];
$out_last = ($byte & 7) << 2;
break;
case 1:
$output .= self::$base32[$out_last | ( $byte & 192) >> 6] .
self::$base32[($byte & 62) >> 1];
$out_last = ($byte & 1) << 4;
break;
case 2:
$output .= self::$base32[$out_last | ($byte & 240) >> 4];
$out_last = ($byte & 15) << 1;
break;
case 3:
$output .= self::$base32[$out_last | ($byte & 128) >> 7] .
self::$base32[($byte & 124) >> 2];
$out_last = ($byte & 3) << 3;
break;
case 4:
$output .= self::$base32[$out_last | ($byte & 224) >> 5] . self::$base32[$byte
& 31];
$out_last = NULL;
break;
}
$bytes++;
}
if (!is_null($out_last))
$output .= self::$base32[$out_last] . str_repeat("=", 7 - (strlen($output) % 8));
return $output;
}
public static function decode32($input)
{
$input = rtrim(strval($input), "=");
$chars = 0;
$out_last = NULL;
$output = "";
while (isset($input{$chars}))
{
$char = $input{$chars};
if (!isset(self::$base32i[$char])) return FALSE;
$char = self::$base32i[$char];
switch ($chars % 8)
{
case 0:
$out_last = $char << 3;
break;
case 1:
$output .= chr($out_last | (($char & 28) >> 2));
$out_last = ($char & 3) << 6;
break;
case 2:
$out_last = $out_last | ($char << 1);
break;
case 3:
$output .= chr($out_last | (($char & 16) >> 4));
$out_last = ($char & 15) << 4;
break;
case 4:
$output .= chr($out_last | (($char & 30) >> 1));
$out_last = ($char & 1) << 7;
break;
case 5:
$out_last = $out_last | ($char << 2);
break;
case 6:
$output .= chr($out_last | (($char & 24) >> 3));
$out_last = ($char & 7) << 5;
break;
case 7:
$output .= chr($out_last | $char);
$out_last = NULL;
break;
}
$chars++;
}
return $output;
}
}