Esempio n. 1
0
  public static void main(String[] args) throws IOException, FileNotFoundException {
    BitReader in = new BitReader(args[0]); // open
    // read in padding
    int padding = in.readBits(8);
    // read in the number of nodes to expect in Huffman Tree
    int numNodes = in.readBits(32);

    TreeNode[] nodes = new TreeNode[numNodes];

    for (int z = 0; z < numNodes; z++) {
      nodes[z] = new TreeLeaf(in.readBits(8), in.readBits(32));
    }

    while (nodes.length > 1) {
      nodes = HuffmanIterate(nodes);
    }

    in.readBits(
        padding); // reads off the padding bits, so that the remainder is simply the encoded file

    String x = "";
    boolean sam;
    TreeNode t;
    t = nodes[0];
    while (!(in.isEof())) {
      if (!t.isLeaf()) {
        sam = in.readBit();
        if (!sam) {
          t = t.getLeft();
        }
        if (sam) {
          t = t.getRight();
        }
      } else {
        x += (char) ((TreeLeaf) t).getChar();
        t = nodes[0];
      }
    }
    x +=
        (char)
            ((TreeLeaf) t)
                .getChar(); // ensures final character is added to file, because while loop stops
    // one char short
    in.close();

    BitWriter out = new BitWriter(args[1]);

    for (int j = 0; j < x.length(); j++) {
      out.writeBits(x.toCharArray()[j], 8);
    }

    out.close();
  }
Esempio n. 2
0
 /**
  * Recur from a symbol back, emitting bits. We recur before emitting to make the bits come out in
  * the right order.
  *
  * @param symbol The symbol to write.
  * @param bitwriter The bitwriter to write it to.
  * @throws JSONException
  */
 private void write(Symbol symbol, BitWriter bitwriter) throws JSONException {
   try {
     Symbol back = symbol.back;
     if (back != null) {
       this.width += 1;
       write(back, bitwriter);
       if (back.zero == symbol) {
         bitwriter.zero();
       } else {
         bitwriter.one();
       }
     }
   } catch (Throwable e) {
     throw new JSONException(e);
   }
 }