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