コード例 #1
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (richTextBox6.Text == " ")
     {
         MessageBox.Show("Please Enter A Text To Compress");
     }
     else
     {
         string decoded = huffmanTree.Decode(encoded);
         richTextBox4.Visible = true;
         richTextBox4.Text    = decoded;
     }
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: enyaaad/Huffman
        static void Main(string[] args)
        {
            BitArray encoded;
            char     input = ' ';
            string   pathtofile;

            Console.WriteLine("Input path to file");
            pathtofile = Console.ReadLine();
            HuffmanTree huffmanTree = new HuffmanTree();

            using (BinaryReader sr = new BinaryReader(new FileStream(pathtofile, FileMode.Open), Encoding.UTF8))
                huffmanTree.Build(input, sr);
            using (BinaryReader sr = new BinaryReader(new FileStream(pathtofile, FileMode.Open), Encoding.UTF8))
                encoded = huffmanTree.Encode(input, sr);

            Console.Write("Encoded ");
            string bytestr = "";
            int    i       = 0;

            while (i < encoded.Length)
            {
                if (bytestr.Length < 8)
                {
                    bytestr += encoded[i] ? 1 : 0.ToString();
                    i++;
                }
                else
                {
                    HuffmanTree.bytes.Add(Convert.ToByte(bytestr, 2));
                    bytestr = "";
                }
            }

            if (bytestr.Length <= 8)
            {
                while (bytestr.Length < 8)
                {
                    bytestr += "0";
                    Node.Delta++;
                }
                HuffmanTree.bytes.Add(Convert.ToByte(bytestr, 2));
            }
            using (StreamWriter sw = new StreamWriter("archive.txt", false))
            {
                sw.Write(Node.EncTree(huffmanTree.Root));
            }

            using (FileStream fs = new FileStream("archive.txt", FileMode.Append))
            {
                fs.Write(HuffmanTree.bytes.ToArray());
                fs.WriteByte(Node.Delta);
            }
            Console.WriteLine();

            huffmanTree.Root = new Node();
            huffmanTree.Decode();
            Console.WriteLine("Decoded");
            Console.WriteLine("All done");
            Console.ReadLine();
        }
コード例 #3
0
        public static void Decode(string arquivo)
        {
            //Carrega arquivo comprimido
            byte[] dados = Arquivo.AbrirEmBytes(arquivo);

            BitArray bits = new BitArray(dados);

            Console.WriteLine("Iniciada a decompressão");
            DateTime dataInicial = DateTime.Now;

            HuffmanTree huffman = new HuffmanTree();

            //Decodificando a árvore huffman
            string huffmanDecoded = huffman.Decode(bits);

            LZWDecoder lZWDecoder = new LZWDecoder();

            //Decodificando LZW
            string conteudo = lZWDecoder.Decode(huffmanDecoded);

            DateTime dataFinal = DateTime.Now;

            string tempoDecorrido = (dataFinal - dataInicial).TotalSeconds.ToString("N2");

            //Contabiliza apenas os tempos para decompressão. Igora tempo de IO
            Console.WriteLine($"Arquivo descomprimido em {tempoDecorrido} segundos");

            Arquivo.Gravar(conteudo, $"{arquivo.Split('.')[0]} - Descomprimido.txt");
        }
コード例 #4
0
ファイル: HuffmanTreeTest.cs プロジェクト: rsgoheen/Compress
        public void TestEncodeDecodeWithCompression()
        {
            var input =
            "He paused for a moment, many recollections overpowering him. Then he went on telling her the history of his life, unfolding to her the story of his hopes and ambitions, describing to her the very home where he was born, and the dark-eyed sister whom he had loved, and with whom he had played over the daisied fields, and through the carpeted woods, and all among the richly tinted bracken. One day he was told she was dead, and that he must never speak her name; but he spoke it all the day and all the night, Beryl, nothing but Beryl, and he looked for her in the fields and in the woods and among the bracken. It seemed as if he had unlocked the casket of his heart, closed for so many years, and as if all the memories of the past and all the secrets of his life were rushing out, glad to be free once more, and grateful for the open air of sympathy.";

             var dict = CharacterFrequencyDictionary.CreateDictionary(input);

             var encodeTree = new HuffmanTree<char>(dict);

             var encode = encodeTree.Encode(input);

             var encodeAsByte = CompressUtil.ConvertToByteArray(encode);

             var secondDict = CharacterFrequencyDictionary.CreateDictionary(
            dict.GetKeysAsByteArray(), dict.GetValuesAsByteArray());

             var encodeAsByteArray = new List<byte>();
             foreach (var b in encodeAsByte)
            encodeAsByteArray.AddRange(CompressUtil.ConvertToBitArray(b));

             if (encode.Length < encodeAsByteArray.ToArray().Length)
            encodeAsByteArray.RemoveRange(encode.Length, encodeAsByteArray.ToArray().Length - encode.Length);

             CollectionAssert.AreEqual(dict, secondDict);
             CollectionAssert.AreEqual(encode, encodeAsByteArray.ToArray());

             var decodeTree = new HuffmanTree<char>(secondDict);
             var decode = decodeTree.Decode(encodeAsByteArray);

             Assert.AreEqual(input, decode);
        }
コード例 #5
0
        public static Bitmap DecompressHuffman(string imgSrc)
        {
            //moram da pocnem odmah otvaranjem fajla i ucitavanjem bajtova redom kako su upisivani
            byte[]      bmpWidth;
            byte[]      bmpHeight;
            byte[]      stride;
            byte[]      downsampleChannels;
            byte[]      dictionarySize;
            byte[]      dictionary;
            byte[]      YDataLen;
            byte[]      CbDataLen;
            byte[]      CrDataLen;
            byte[]      imageData;
            HuffmanTree tree = new HuffmanTree();

            using (var reader = new BinaryReader(File.Open(imgSrc, FileMode.Open)))
            {
                bmpWidth           = reader.ReadBytes(4);
                bmpHeight          = reader.ReadBytes(4);
                stride             = reader.ReadBytes(4);
                downsampleChannels = reader.ReadBytes(4);

                YDataLen  = reader.ReadBytes(4);
                CbDataLen = reader.ReadBytes(4);
                CrDataLen = reader.ReadBytes(4);

                dictionarySize = reader.ReadBytes(4);

                int dictSize = BitConverter.ToInt32(dictionarySize, 0);

                dictionary = reader.ReadBytes(dictSize);
                tree.DeserializeDictionary(dictionary);

                List <byte> compressedData = new List <byte>();
                while (reader.BaseStream.Position != reader.BaseStream.Length)
                {
                    compressedData.Add(reader.ReadByte());
                }

                imageData = tree.Decode(new BitArray(compressedData.ToArray()));
            }

            int width                = BitConverter.ToInt32(bmpWidth, 0);
            int height               = BitConverter.ToInt32(bmpHeight, 0);
            int strideInt            = BitConverter.ToInt32(stride, 0);
            int downampleChannelsInt = BitConverter.ToInt32(downsampleChannels, 0);
            int yDataLen             = BitConverter.ToInt32(YDataLen, 0);
            int cbDataLen            = BitConverter.ToInt32(CbDataLen, 0);
            int crDataLen            = BitConverter.ToInt32(CrDataLen, 0);


            DownsampleFormat format = new DownsampleFormat(strideInt, width, height, yDataLen, cbDataLen, crDataLen, downampleChannelsInt);

            format.data = imageData;
            Downsampling sampling = new Downsampling();

            return(sampling.RestoreBitmap(format));
        }
コード例 #6
0
        private string Decode(BitArray bytes)
        {
            //First convert the compressed output to a bit array again again and skip trailing bits.
            //var bytes = Encoding.ASCII.GetBytes(input);
            _tree.BuildTree();

            var boolAr = bytes.Cast <bool>().Take(_tree.BitCountForTree).ToArray();

            var binary = new BitArray(boolAr);

            return(_tree.Decode(binary));
        }
コード例 #7
0
        public void TestHuffmanCodingProblem()
        {
            HuffmanTree hfmTree = new HuffmanTree();
            string      input   = "sankara loves devi";

            hfmTree.Build(input);

            BitArray encoded = hfmTree.Encode(input);

            string decoded = hfmTree.Decode(encoded);

            Assert.IsTrue(input == decoded);
        }
コード例 #8
0
        public void HuffmanTree_Encode_Decode(int count)
        {
            var sourceStr   = CreateString(count);
            var sourceBytes = Encoding.UTF8.GetBytes(sourceStr);
            var cipherBytes = HuffmanTree.Encode(sourceBytes);
            var plainBytes  = HuffmanTree.Decode(cipherBytes);
            var plainStr    = Encoding.UTF8.GetString(plainBytes);

            Assert.Equal(sourceStr.Length, plainStr.Length);
            Assert.Equal(sourceStr, plainStr);
            Assert.Equal(sourceBytes.Length, plainBytes.Length);
            Assert.Equal(sourceBytes, plainBytes);
        }
コード例 #9
0
ファイル: HuffmanTreeTest.cs プロジェクト: rsgoheen/Compress
        public void TestEncodeDecode()
        {
            var input = "abcdef 123 a test string baba abba 234";
            var dict  = CharacterFrequencyDictionary.CreateDictionary(input);

            var encodeTree = new HuffmanTree <char>(dict);

            var z = encodeTree.Encode(input);

            var decodeTree = new HuffmanTree <char>(dict);
            var decode     = decodeTree.Decode(z);

            Assert.AreEqual(input, decode);
        }
コード例 #10
0
ファイル: HuffmanTreeTest.cs プロジェクト: rsgoheen/Compress
        public void TestEncodeDecode()
        {
            var input = "abcdef 123 a test string baba abba 234";
             var dict = CharacterFrequencyDictionary.CreateDictionary(input);

             var encodeTree = new HuffmanTree<char>(dict);

             var z = encodeTree.Encode(input);

             var decodeTree = new HuffmanTree<char>(dict);
             var decode = decodeTree.Decode(z);

             Assert.AreEqual(input, decode);
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: rsgoheen/Compress
        public static void DecompressFile(string inputfilename, string outputFilename)
        {
            Console.WriteLine("Decompressing file {0} to {1}", inputfilename, outputFilename);

             HuffmanTree<char> huffmanTree;
             var encodedStream = new List<byte>();

             using (var fs = new FileStream(inputfilename, FileMode.Open, FileAccess.Read))
             {
            var keyLengthArray = new byte[4];
            var valueLengthArray = new byte[4];

            fs.Read(keyLengthArray, 0, 4);
            fs.Read(valueLengthArray, 0, 4);

            var keyLength = BitConverter.ToInt32(keyLengthArray, 0);
            var valueLength = BitConverter.ToInt32(valueLengthArray, 0);

            var keyArray = new byte[keyLength];
            var valueArray = new byte[valueLength];

            fs.Read(keyArray, 0, keyLength);
            fs.Read(valueArray, 0, valueLength);

            var compressedLengthArray = new byte[4];
            fs.Read(compressedLengthArray, 0, 4);
            var compressedLength = BitConverter.ToInt32(compressedLengthArray, 0);

            var dict = CharacterFrequencyDictionary.CreateDictionary(keyArray, valueArray);
            huffmanTree = new HuffmanTree<char>(dict);

            int record;
            while ((record = fs.ReadByte()) != -1)
               encodedStream.AddRange(CompressUtil.ConvertToBitArray((byte)record));

            if (encodedStream.Count() > compressedLength)
               encodedStream.RemoveRange(compressedLength, encodedStream.Count() - compressedLength);
             }

             using (var fsw = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
             using (var sr = new StreamWriter(fsw))
            sr.Write(huffmanTree.Decode(encodedStream));

             Console.WriteLine("Compression complete.");
        }
コード例 #12
0
        private void button9_Click(object sender, EventArgs e)
        {
            var watch  = new System.Diagnostics.Stopwatch();
            var watch2 = new System.Diagnostics.Stopwatch();

            for (int s = min; s < max; s += step)
            {
                generatingbench(s);
                BitArray temp = null;
                for (int i = 0; i < nor; i++)
                {
                    watch.Restart();
                    compress(inputbench.ToString());
                    huffmanTree = new HuffmanTree();
                    huffmanTree.Build(compressed.ToString());
                    BitArray encoded2 = huffmanTree.Encode(compressed.ToString());
                    benchmarktime1 += watch.Elapsed.TotalMilliseconds;
                    if (i == 0)
                    {
                        temp = huffmanTree.Encode(compressed.ToString());
                    }
                    watch.Stop();
                }
                //==================================================================================================
                for (int i = 0; i < nor; i++)
                {
                    watch2.Restart();
                    decompress();
                    string decoded = huffmanTree.Decode(temp);
                    benchmarktime2 += watch2.Elapsed.TotalMilliseconds;
                    watch2.Stop();
                }
                if (s == min)
                {
                    this.richTextBox13.Text = "Data Size \t" + "Compress time \t" + "Decompress Time \t" + "\n" + "=====================================================" + "\n";
                }
                this.richTextBox13.Text += s + "\t\t" + Math.Round((benchmarktime1 / nor), 3).ToString() + "\t\t" + Math.Round((benchmarktime2 / nor), 3).ToString() + "\n";
                benchmarktime1           = 0;
                benchmarktime2           = 0;
            }
        }
コード例 #13
0
ファイル: HuffmanTreeTest.cs プロジェクト: rsgoheen/Compress
        public void TestEncodeDecodeWithCompression()
        {
            var input =
                "He paused for a moment, many recollections overpowering him. Then he went on telling her the history of his life, unfolding to her the story of his hopes and ambitions, describing to her the very home where he was born, and the dark-eyed sister whom he had loved, and with whom he had played over the daisied fields, and through the carpeted woods, and all among the richly tinted bracken. One day he was told she was dead, and that he must never speak her name; but he spoke it all the day and all the night, Beryl, nothing but Beryl, and he looked for her in the fields and in the woods and among the bracken. It seemed as if he had unlocked the casket of his heart, closed for so many years, and as if all the memories of the past and all the secrets of his life were rushing out, glad to be free once more, and grateful for the open air of sympathy.";

            var dict = CharacterFrequencyDictionary.CreateDictionary(input);

            var encodeTree = new HuffmanTree <char>(dict);

            var encode = encodeTree.Encode(input);

            var encodeAsByte = CompressUtil.ConvertToByteArray(encode);

            var secondDict = CharacterFrequencyDictionary.CreateDictionary(
                dict.GetKeysAsByteArray(), dict.GetValuesAsByteArray());

            var encodeAsByteArray = new List <byte>();

            foreach (var b in encodeAsByte)
            {
                encodeAsByteArray.AddRange(CompressUtil.ConvertToBitArray(b));
            }

            if (encode.Length < encodeAsByteArray.ToArray().Length)
            {
                encodeAsByteArray.RemoveRange(encode.Length, encodeAsByteArray.ToArray().Length - encode.Length);
            }

            CollectionAssert.AreEqual(dict, secondDict);
            CollectionAssert.AreEqual(encode, encodeAsByteArray.ToArray());

            var decodeTree = new HuffmanTree <char>(secondDict);
            var decode     = decodeTree.Decode(encodeAsByteArray);

            Assert.AreEqual(input, decode);
        }
コード例 #14
0
 private void button2_Click(object sender, EventArgs e)
 {
     richTextBox2.Text = "";
     richTextBox2.AppendText(htree.Decode(encoded));
 }
コード例 #15
0
        void backWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            System.ComponentModel.BackgroundWorker b = sender as System.ComponentModel.BackgroundWorker;
            int samples = 32;

            short[] buffer = new short[samples];
            bw = new BinaryWriter(File.Open(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Code.huf", FileMode.Create));

            stream = Bass.BASS_StreamCreateFile(path, 0L, 0L, BASSFlag.BASS_STREAM_DECODE);

            ww = new WaveWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/HufSound.wav", stream, true);
            int  mult = 0;
            long len  = Bass.BASS_ChannelGetLength(stream, BASSMode.BASS_POS_BYTES);

            while (Bass.BASS_ChannelIsActive(stream) == BASSActive.BASS_ACTIVE_PLAYING)
            {
                int length = Bass.BASS_ChannelGetData(stream, buffer, samples * 2);
                mult++;
                b.ReportProgress((int)(((samples * mult) * 100) / len * 2));
                List <short> listBuffer = new List <short>();
                HuffmanTree  tree       = new HuffmanTree();
                if (length > 0)
                {
                    listBuffer.AddRange(buffer);
                    short[] auxbuf = new short[buffer.Length];
                    auxbuf = buffer;
                    canvasWavComp.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.SystemIdle, new Action(delegate
                    {
                        //Whole Wave
                        //double xScale = canvasWavComp.Width / samples;

                        //Formula by Manuel García. Dude you're amazing.
                        //NOTE: multiply by 2 'cos I supoused some relation with Nyquist Theorem
                        double xScale = (canvasWavComp.Width * samples) / len * 2;

                        double yScale      = (canvasWavComp.Height / (double)(amplitude * 2)) * ((double)amplitude / MAX_AMP);
                        Polyline graphLine = new Polyline();

                        //This Line is used to move on the x axis
                        Canvas.SetLeft(graphLine, xAxis);

                        graphLine.Stroke          = new SolidColorBrush(Color.FromRgb(244, 67, 54));
                        graphLine.StrokeThickness = 2;
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            graphLine.Points.Add(new Point(xScale * i, (canvasWavComp.Height / 2) - (buffer[i] * yScale)));
                        }
                        xAxis += xScale;
                        //canvasWavComp.Children.Clear();
                        canvasWavComp.Children.Add(graphLine);
                    }));
                    double entaux = 0;
                    foreach (var sym in listBuffer.GroupBy(i => i))
                    {
                        NodeHuf nodeHuf = new NodeHuf();
                        nodeHuf.Symbol    = sym.Key;
                        nodeHuf.Frequency = sym.Count();
                        nodeHuf.Right     = nodeHuf.Left = null;
                        tree.Add(nodeHuf);
                        double prob = (double)nodeHuf.Frequency / samples;
                        //entropy -= prob * (Math.Log(prob) / Math.Log(2));
                        entaux   += prob * Math.Log(1 / (prob), 2);
                        entauxlbl = entaux;
                    }
                    entropy += entaux;
                    entcount++;
                    tree.Build();


                    //Encode
                    System.Collections.BitArray encoded = tree.Encode(auxbuf);
                    byte[] arrayBytes = new byte[encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1)];
                    encoded.CopyTo(arrayBytes, 0);
                    File.WriteAllBytes("Compress.bin", arrayBytes);

                    //Decode
                    byte[] data;
                    Stream fs = File.OpenRead("Compress.bin");
                    data = new byte[fs.Length];
                    fs.Read(data, 0, data.Length);
                    System.Collections.BitArray bitDec = new System.Collections.BitArray(data);

                    short[] decoded = tree.Decode(bitDec);
                    if (decoded.Length > 0)
                    {
                        ww.Write(decoded, length);
                    }
                    bw.Write(data);
                    fs.Close();
                }
            }
            //Delete temporaly file
            File.Delete("Compress.bin");

            //Close de Stream WAV ww
            ww.Close();

            //If you not add this line, the backgroundworker will be restat but when file is create again
            //there will be an incongruence because the bw never was closed.
            bw.Close();

            entropy /= entcount;// (len / samples);
            entcount = 0;
        }
コード例 #16
0
        private void buttonRun_Click(object sender, EventArgs e)
        {
            //Сначала для классического алгритма
            if (textBoxOutC.Text != "")
            {
                labelOutС.Enabled   = true;
                textBoxOutC.Enabled = true;
                //получаем частотный словарь
                FrequencyDictionary frequencyDictionary = new FrequencyDictionary(openFileDialogInput.FileName);
                SizeDictionaryC             = frequencyDictionary.CountWord;
                textBoxSizeDictionaryС.Text = SizeDictionaryC.ToString() + "  слов";

                //построение дерева
                var         startTime   = System.Diagnostics.Stopwatch.StartNew();
                HuffmanTree huffmanTree = new HuffmanTree(frequencyDictionary);
                startTime.Stop();
                var resultTime = startTime.Elapsed.TotalSeconds;

                //string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                //        resultTime.Hours,
                //        resultTime.Minutes,
                //        resultTime.Seconds,
                //        resultTime.Milliseconds);
                textBoxTimeBuildTree.Text = resultTime.ToString();

                //Кодирование
                startTime = System.Diagnostics.Stopwatch.StartNew();
                huffmanTree.Encode(@openFileDialogInput.FileName, @textBoxOutC.Text);
                startTime.Stop();
                resultTime = resultTime + startTime.Elapsed.TotalSeconds;
                //elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                //        resultTime.Hours,
                //        resultTime.Minutes,
                //        resultTime.Seconds,
                //        resultTime.Milliseconds);
                textBoxSpeedEncodeС.Text = resultTime.ToString();

                //сбрасываем дерево
                huffmanTree = new HuffmanTree();

                //Декодируем
                startTime = System.Diagnostics.Stopwatch.StartNew();
                huffmanTree.Decode(@textBoxOutC.Text, @textBoxDecodeFileC.Text);
                startTime.Stop();
                resultTime = startTime.Elapsed.TotalSeconds;
                //elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                //        resultTime.Hours,
                //        resultTime.Minutes,
                //        resultTime.Seconds,
                //        resultTime.Milliseconds);
                textBoxSpeedDecodeС.Text = resultTime.ToString();

                //Получаем другие статитстики
                SizeFileEncodeC           = new FileInfo(@textBoxOutC.Text).Length;
                textBoxSizeCompressС.Text = SizeFileEncodeC.ToString() + "  байт";

                textBoxCoefficientCompressС.Text = ((SizeFileInput * 1.0) / SizeFileEncodeC).ToString();

                groupBoxClassicHuffmanAlgo.Enabled = true;
            }

            //Потом для адаптивного
            if (textBoxOutA.Text != "")
            {
                labelOutA.Enabled   = true;
                textBoxOutA.Enabled = true;

                HuffmanAdaptiveTree huffmanAdaptiveTree = new HuffmanAdaptiveTree();
                //Кодирование
                var startTime = System.Diagnostics.Stopwatch.StartNew();
                huffmanAdaptiveTree.Encode(@openFileDialogInput.FileName, @textBoxOutA.Text);
                startTime.Stop();
                var resultTime = startTime.Elapsed.TotalSeconds;
                //var elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                //        resultTime.Hours,
                //        resultTime.Minutes,
                //        resultTime.Seconds,
                //        resultTime.Milliseconds);
                textBoxSpeedEncodeA.Text = resultTime.ToString();

                //сбрасываем дерево
                huffmanAdaptiveTree = new HuffmanAdaptiveTree();
                huffmanAdaptiveTree.Reset();

                //Декодируем
                startTime = System.Diagnostics.Stopwatch.StartNew();
                huffmanAdaptiveTree.Decode(@textBoxOutA.Text, @textBoxDecodeFileA.Text);
                startTime.Stop();
                resultTime = startTime.Elapsed.TotalSeconds;
                //elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                //        resultTime.Hours,
                //        resultTime.Minutes,
                //        resultTime.Seconds,
                //        resultTime.Milliseconds);
                textBoxSpeedDecodeA.Text = resultTime.ToString();

                //Получаем другие статитстики
                SizeFileEncodeA           = new FileInfo(@textBoxOutA.Text).Length;
                textBoxSizeCompressA.Text = SizeFileEncodeA.ToString() + "  байт";

                textBoxCoefficientCompressA.Text = ((SizeFileInput * 1.0) / SizeFileEncodeA).ToString();

                groupBoxAdaptiveHuffmanAlgo.Enabled = true;
            }
        }
コード例 #17
0
        static void Main(string[] args)
        {
            int    action;
            string inputFilePath;
            string inputFileName;
            string outputFileName;

            int.TryParse(args[0], out action);

            if (args.Length < 4 || (args.Length == 4 && action != 1 && action != 2))
            {
                action = 0;
                Console.WriteLine("Please choose option:");
                Console.WriteLine("1 - encode");
                Console.WriteLine("2 - decode");
                string option = Console.ReadLine();
                action = int.Parse(option);

                while (action != 1 && action != 2)
                {
                    Console.WriteLine("there is no such option");
                    Console.WriteLine("1 - encode");
                    Console.WriteLine("2 - decode");
                    option = Console.ReadLine();
                    action = int.Parse(option);
                }

                Console.WriteLine("Please enter the full path of the input file");
                inputFilePath = Console.ReadLine();
                Console.WriteLine("Please enter the name of the input file");
                inputFileName = Console.ReadLine();
                Console.WriteLine("Please enter the name of the output file");
                outputFileName = Console.ReadLine();
            }
            else
            {
                action         = int.Parse(args[0]);
                inputFilePath  = args[1];
                inputFileName  = args[2];
                outputFileName = args[3];
            }

            string inputFileFullName  = inputFilePath + "\\" + inputFileName;
            string outputFileFullName = inputFilePath + "\\" + outputFileName;

            bool isSucceeded;

            if (action == 1 || action == 2)
            {
                if (action == 1)
                {
                    isSucceeded = HuffmanTree.Encode(inputFileFullName, outputFileFullName);
                }
                else
                {
                    isSucceeded = HuffmanTree.Decode(inputFileFullName, outputFileFullName);
                }

                Console.WriteLine(isSucceeded ? "The operation was successful" : "Operation failed, check if the input file exist");
            }
        }
コード例 #18
0
 /// <summary>
 ///     Decodes this message using the specified huffman tree.
 /// </summary>
 /// <param name="huffmanTree">The huffman tree to use.</param>
 /// <returns>The decoded message.</returns>
 public DemoMessage Decode(HuffmanTree huffmanTree)
 {
     return new DemoMessage(huffmanTree.Decode(new BitArray(Data)));
 }