Example #1
0
 public static function decode($bits)
 {
     $result = Huffman::decodeTree($bits);
     $startIndex = $result[0];
     $tree = $result[1];
     $current = $tree->root;
     $s = "";
     $i = $startIndex;
     while ($i < count($bits)) {
         if ($current->left && $current->right) {
             if ($bits[$i++]) {
                 $current = $current->right;
             } else {
                 $current = $current->left;
             }
         } else {
             if ($current->left || $current->right) {
                 throw new Exception("Leaf must not have any children.");
             }
             $s .= $current->symbol;
             $current = $tree->root;
         }
     }
     if ($current->left || $current->right) {
         throw new Exception("Leaf expected at end of input.");
     }
     $s .= $current->symbol;
     return $s;
 }