public byte[] DecompressData(byte[] compressedData, int tailZeroCount) { LogUtil.Log("Decompressing data..."); List <byte> originalData = new List <byte>(); int remainBitsInByte = 8; long operatingByteIndex = 0; byte operatingByte = compressedData[0]; HuffmanNode currentNode = RootNode; while (true) { // Check if reached the end of data if (operatingByteIndex == compressedData.LongLength - 1 && remainBitsInByte == tailZeroCount % 8) { return(originalData.ToArray()); } // Get the highest bit of current byte as part of path currentNode = (operatingByte >> 7) == L_BIT ? currentNode.LeftChild : currentNode.RightChild; // If leaf node is found, get original byte of string and reset current node if (currentNode.IsLeafNode) { originalData.Add(currentNode.NodeValue); currentNode = RootNode; } // Check if need to move to next bit remainBitsInByte--; if (remainBitsInByte == 0) { remainBitsInByte = 8; operatingByteIndex++; //Console.WriteLine(compressedData.LongLength - operatingByteIndex); if (operatingByteIndex == compressedData.LongLength) { return(originalData.ToArray()); } operatingByte = compressedData[operatingByteIndex]; } else { operatingByte <<= 1; } } }
/// <summary> /// Visit all nodes recursively and save the path of leaf node to path dictionary /// </summary> /// <param name="node">Next node</param> /// <param name="nextString">String for next node</param> /// <param name="pathDictionary">Dictionary for saving all strings</param> private void GetPathOfNodeAndChildren(HuffmanNode node, string nextString, Dictionary <byte, string> pathDictionary) { if (node.IsLeafNode) { // Save current string to dict pathDictionary.Add(node.NodeValue, nextString); } if (node.LeftChild != null) { // If has left child, visit it GetPathOfNodeAndChildren(node.LeftChild, nextString + "L", pathDictionary); } if (node.RightChild != null) { // If has right child, visit it GetPathOfNodeAndChildren(node.RightChild, nextString + "R", pathDictionary); } }