public EncodedFile encodeFile() { char[] charset = getCharset(); int[] weights = getCharFrequencies(charset); HuffmanTree tree = new HuffmanTree(charset, weights); string[] codes = tree.getCodes(charset); string encoded = encodeToString(charset, codes); string huffmanData = tree.getBinaryRepresentation(); Console.WriteLine(tree.getHuffmanCode(',')); //TEST TEST TEST EncodedFile enf = new EncodedFile("E:\\Users\\Alexander Weaver\\My Documents\\encodedTEST.hct", EncodedFile.CREATE_NEW); writeEncodedFile(enf, huffmanData, encoded); return enf; }
//Produces a lookup dictionary which maps a given encoded binary symbol, in string format to the symbol's corresponding ASCII character private Dictionary<string, char> getCodeDictionary(HuffmanTree tree) { Dictionary<string, char> table = new Dictionary<string, char>(); char[] charset = tree.getCharset(); for (int i = 0; i < charset.Length; ++i) { try { table.Add(tree.getHuffmanCode(charset[i]), charset[i]); } catch { continue; //... } } return table; }
//Reads the huffman data at the beginning of the file, and returns the corresponding huffman tree private HuffmanTree getTreeFromFile(byte[] file, byte huffmanDataLength) { byte[] hData = new byte[huffmanDataLength]; Array.Copy(file, 1, hData, 0, huffmanDataLength); string huffmanData = ""; for (int i = 0; i < hData.Length; ++i) { huffmanData += Convert.ToString(hData[i], 2).PadLeft(8, '0'); } HuffmanTree tree = new HuffmanTree(huffmanData); return tree; }