private void EncodeBytes(byte[] source, string dictionary_file_path, string destination_file_path, ref DecodingInfo info) { var priorities = CountPriorities(source); var binaryTree = new HuffmanBinaryTree(priorities); byte[] destinationBytes = FillInByteDestination(source, binaryTree); File.WriteAllBytes(destination_file_path, destinationBytes); info.CodeDict = binaryTree.CodeDict; info.MinCodeLength = binaryTree.MinCodeLength; IFormatter formatter = new BinaryFormatter(); Stream DictStream = new FileStream(dictionary_file_path, FileMode.Create, FileAccess.Write, FileShare.None); formatter.Serialize(DictStream, info); File.SetAttributes(dictionary_file_path, FileAttributes.Hidden); DictStream.Close(); }
/* private HuffmanBinaryTree CreateTree(Dictionary<byte, long> byte_priorities) * { * var nodes = new List<Node>(); * * foreach (var kvp in byte_priorities) * { * nodes.Add(new Node(kvp.Key, kvp.Value)); * } * * while (nodes.Count > 1) * { * nodes.Sort(Node.Compare); * * nodes[0] = new Node(nodes[0], nodes[1]); * nodes.RemoveAt(1); * } * if(nodes.Count == 0) * { * return new HuffmanBinaryTree(null); * } * return new HuffmanBinaryTree(nodes[0]); * }*/ private byte[] FillInByteDestination(byte[] source, HuffmanBinaryTree binaryTree) { canc_token.ThrowIfCancellationRequested(); int position = 0; Byte temp = 0; Code a; List <byte> destination = new List <byte>(); int processed = 0; foreach (byte character in source) { a = binaryTree.GetCode(binaryTree.Root, character); for (int j = 0; j < a.BitNumber; j++) { byte CurrentBit = a.Number.GetBit((int)(32 - a.BitNumber + j)); if (position < 8) { temp = (Byte)(temp * 2 + CurrentBit); position++; } if (position == 8) { destination.Add(temp); temp = 0; position = 0; } } processed = processed + 1; if (processed % interval == 0) { PartialPerformStep(1); } if (position != 0 && processed == source.Length) { while (position < 8) { temp = (Byte)(temp * 2); position++; } destination.Add(temp); } if (canc_token.IsCancellationRequested) { canc_token.ThrowIfCancellationRequested(); } } return(destination.ToArray()); }