Alfredo Liardo
Alfredo Liardo

Reputation: 115

How to serialize the Huffman tree in c++

As the title suggest I want to serialize my huffman tree as header of my encoded file. I have seen this question:efficient way to storing huffman tree

I understand how it works, but I can not apply it, i have written this code:

typedef Node<char,unsigned long> Node;

void Encoder::EncodeNode(Node node)
{
if (node.left == &Node::NIL and node.right == &Node::NIL)
   {
    writeBit(1);
    outFile << node.first;
   }
else
   {
    writeBit(0);
    EncodeNode(*node.left);
    EncodeNode(*node.right);
   }
}

this is the writeBit function that I use to encode characters:

void Encoder::writeBit(unsigned short bit)
{
if(bit < 2){//if not EOF
    if(bit){
        byteBuffer |= (1 << (7 - byteCursor));
    }
    byteCursor++;
    if (byteCursor == 8) {
        outFile << byteBuffer;
        byteBuffer = 0;
        byteCursor = 0;
    }
}else{
    outFile << bit;
    }
}

but with this function I'm not able to write a single bit. Any advice?

UPDATE: Could go well?:

void Encoder::EncodeNode(Node node)
{
if (node.left == &Node::NIL and node.right == &Node::NIL)
{
    char c = node.first;
    writeBit(1);
    for (unsigned short i = 0; i < 8; i++) {
        writeBit(c & (1 << (7-i)));
    }
}
else
{
    writeBit(0);
    EncodeNode(*node.left);
    EncodeNode(*node.right);
}
}

Upvotes: 0

Views: 2246

Answers (1)

Mark Adler
Mark Adler

Reputation: 112374

See Ezran's answer to the question you linked (as opposed to the accepted answer). That is the most efficient, as well as the simplest approach. You do not need to encode the tree structure at all. All you need to send are the number of bits for each symbol.

Upvotes: 2

Related Questions