Help regarding huffman compression
Hi,
i am making a compression program using huffman algorithm.i understand how to create huffman tree for decoding.but for the purpose of compression i am having problem understanding how to assign codes.also how can i write on a file the codes in the form of bits.if any one out there can help please reply.
First you figure out the "weights" of the bytes in the file. The weight of a byte is just the number of times it appears.
Next you start with n trees, where n is the number of bytes with non-zero weights. Each tree is of depth 1 and contains one of the bytes.
Now, you pick two trees with the lowest weight and combine them into a new tree (with the left branch one of the tree and right branch the other) the new weight of this tree is the sum of the weights of the combined trees. Keep doing that until there''s only one tree, and that''s it.
Also, to write out an arbitrary number of bits, just create a "write_bit" function which accumulates the bits until it''s got a complete byte, then writes that out. To write n-bits, just call your "write_bit" function n times. It''s not the fastest way, but it''s the easiest...
codeka.com - Just click it.
Next you start with n trees, where n is the number of bytes with non-zero weights. Each tree is of depth 1 and contains one of the bytes.
Now, you pick two trees with the lowest weight and combine them into a new tree (with the left branch one of the tree and right branch the other) the new weight of this tree is the sum of the weights of the combined trees. Keep doing that until there''s only one tree, and that''s it.
Also, to write out an arbitrary number of bits, just create a "write_bit" function which accumulates the bits until it''s got a complete byte, then writes that out. To write n-bits, just call your "write_bit" function n times. It''s not the fastest way, but it''s the easiest...
codeka.com - Just click it.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement