Reputation: 1613
I have build the huffman tree. But I have no idea to store the code to bits due to I don't know how
to handle the variable length.
I want to create a table that store the huffman code in bits for print the encoded result.
I cannot use the STL containter like bitset.
I have try like that
void traverse( string code = "")const
{
if( frequency == 0 ) return;
if ( left ) {
left->traverse( code + '0' );
right->traverse( code + '1' );
}
else {//leaf node
huffmanTable[ch] = code;
}
}
Can you give me some algorithm to handle it?
I want to store the '0' use 1 bit and "1" use 1 bit.
Thx in advance.
Upvotes: 1
Views: 1129
Reputation: 36527
Basically I'd use one of two different approaches here, based on the maximum key length/depth of the tree:
If you've got a fixed length and it's shorter than your available integer data types (like long int
), you can use the approach shown by perreal.
If you don't know the maximum depth and think you might be running out of space, I'd use std::vector<bool>
as the code value. This is a special implementation of the vector using a single bit per value (essentially David's approach).
Upvotes: 1
Reputation: 98088
You can use a fixed size structure to store the table and just bits to store encoded input:
struct TableEntry {
uint8_t size;
uint8_t code;
};
TableEntry huffmanTable[256];
void traverse(uint8_t size; uint8_t code) const {
if( frequency == 0 ) return;
if ( left ) {
left->traverse(size+1, code << 1 );
right->traverse(size+1, (code << 1) | 1 );
}
else {//leaf node
huffmanTable[ch].code = code;
huffmanTable[ch].size = size;
}
}
For encoding, you can use the algorithm posted by David.
Upvotes: 1
Reputation: 182829
You'll need a buffer, a variable to track the size of the buffer in bytes, and a variable to track the number of valid bits in the buffer.
To store a bit:
Check if adding a bit will increase the number of bytes stored. If not, skip to step 4.
Is there room in the buffer to store an additional byte? If so, skip to step 4.
Reallocate a storage buffer a few bytes larger. Copy the existing data. Increase the variable holding the size of the buffer.
Compute the byte position and bit position at which the next bit will be stored. Set or clear that bit as appropriate.
Increment the variable holding the number of bits stored.
Upvotes: 2