I want to save Huffman codes into a file. How can I do this? I am saving Huffman codes into a string but size of generated file is bigger than Original file.
A very simple approach is to write one bit at a time with something like the following:
to read back a sigle bit the procedure is symmetrical
of course this is just the simplest approach, but I'd wait before worrying about code speed until you are first able to save and load correctly your encoded data.
Suppose you have the following Huffman coded symbols
and that you want to encode the sequence
then you would call in order
The actual bytes written would therefore be
(Note that the code shown starts from the least significant bit, i.e. you should read the bit sequences inside the parenthesis from right to left if you want to recognize the symbols).
I believe what you are saving is a string of 1's and 0's. A true huffman code needs to be saved in binary and then parsed later on. If you are merely saving the output as a string you are defeating the purpose of a huffman code, each 0 and 1 is 8bits instead of 1.
You are probably saving the entire byte for each pattern/letter.
Let's say e is the most common letter. It will have a bit pattern of 0.
Let's say z is the least common letter it will have some pattern starting with 1. Let's just assign it to be 1111 111.
The file you want to be writing will be this:
You are PROBABLY writing this:
0000 0000 0111 1111.
You need to take advantage of bitwise operations to do this.