I'm trying to build a Huffman encoder that can read the bytes out of a text file and convert them to Huffman codes. And I need to be able to decode.
So far I've been able to read the bytes from a file and put them in an tree that is based on a double-linked list representing the Huffman encoding. I have a text file with this text: "abcabcabd". This is the tree I generate:
My goal is to read out the tree and put the whole output in an array. My expected array would look like this: "1, 01, 000, 1, 01, 000, 1, 01, 001"
The only problem is I have no idea how to determine where what letter is positioned. I want to do it using the 1/0 method.
So my question here is: how do I determine where the 'byte' codes are located. Would I do it in a while loop? I want it to be variable so creating an library isn't possible. I have tried this:
First I create my tree:
public static void mBitTree()
{
W = H;
if (W.N != null)
{
int Fn = W.A;
int Sn = W.N.A;
int Cn = Fn + Sn;
cZip n = new cZip(0, Cn);
//First Set new node to link to subnodes.
n.L = W;
n.R = W.N;
if (W.N.N != null)
{
n.N = H.N.N;
H.N.N.P = n;
H.N.N = n;
//Safe and set new head and fix links.
W = H.N.N;
H.N.N = null;
H.N.P = null;
H.N = null;
H = W;
}
//this means there were 2 nodes left. so the newly created one will become Head ant Tail and the tree is complete.
else
{
H.N.P = null;
H.N = null;
H = n;
T = n;
}
}
else
{
return;
}
}
The top node from where I start is H and T. Also it has an L and R. The first thing needed to be checked is H.L is not equal to current. Then go to H.R.L, then H.R.R.L and so on. If I have a bigger text file this needs to work as well. So I created something like this:
public static string[] mCodedchain(uint[] count, byte[] bytesInFile)
{
int counter = 0;
for (int i = 0; i < count.Length; i++) { if (count[i] != 0) counter = counter + (int)count[i]; }
string[] codedArray = new string[counter];
for (int i = 0; i < bytesInFile.Length; i++)
{
int number = 0;
while ((int)bytesInFile[i] != number )
{
number = H.L.V //and if not H.L Add R in between to go to H.R.L.V
}
}
return codedArray;
}
But have no clue as to how I would build up the while loop. I've tried a lot of things but this one seems the most valid to use, but I can't get it to work.
I'm not quite sure if this question is clear. But I hope it is.
Thanks in advance, and happy coding.