简体   繁体   中英

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);
}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM