1
votes

I have successfully built my Huffman tree and I have a method that traverses the the tree and saves the Huffman code for each character as a String of 1s and 0s:

    public void encode(HuffmanNode node, String aux) {

    if (!node.isLeaf()) {
        if (node.getLeft() != null) {
            aux = aux + "0";
            encode(node.getLeft(), aux);
        }
        if (node.getRight() != null){
            aux = aux + "1";
            encode(node.getRight(), aux);
        }
    } else {
        //building a character-code pair and add to keyMap
        keyMap.put(new Character(node.getCh()), aux);
    }
}

where keyMap is a HashMap that maps each character to its Huffman-code.

However, saving Huffman-codes as Strings only increases the size of the encoded file instead of compressing it, since you need a String of 0s and 1s to represent a single character. So is there a way to save the code as binary bits instead of String? Thx in advance.

1

1 Answers

2
votes

Don't use a String to store the binary result, use a java.util.BitSet.

It does exactly what you want, allowing you to set individual bits by index position.

When you are ready to extract the value in binary you can use toByteArray().