예제 #1
0
        public void Can_Read_Bytes_From_File()
        {
            //1)read bytes from file into GLOBAL string in the form of zeros and ones
            //2)loop over this string(IEnumerable<char>) and when finding prefix code
            //delete it from GLOBAL and append symbol(which has that prefix code) to DECODED_TEXT string
            //3)write DECODED_TEXT into file with name <previous_Name>_decoded.txt
            string input       = "01110100011001010111001101110100";
            string pathForFile = PathTestDir + "geig_encoded";

            int numBytes       = (int)Math.Ceiling(input.Length / 8m);
            var bytesAsStrings =
                Enumerable.Range(0, numBytes)
                .Select(i => input.Substring(8 * i, Math.Min(8, input.Length - 8 * i)));

            byte[] bytes = bytesAsStrings.Select(s => Convert.ToByte(s, 2)).ToArray();
            using (FileStream fs = File.OpenWrite(pathForFile))
            {
                fs.Write(bytes);
                fs.Close();
            }

            using (FileStream fs = File.OpenRead(pathForFile))
            {
                BinaryReader br         = new BinaryReader(fs);
                byte[]       outBytes   = br.ReadBytes(numBytes);
                string       bRepresent = "";
                foreach (var b in outBytes)
                {
                    bRepresent += HuffmanWrapper <char> .GetByteString(b);
                }

                Assert.AreEqual(input, bRepresent);
            }
        }
예제 #2
0
        public void HuffmanCompressDecompressTest()
        {
            var hufWrapper = new HuffmanWrapper <char>();

            hufWrapper.Huffman(Source);

            Dictionary <char, List <int> > huffmanDictionary =
                hufWrapper.Encode();

            foreach (char c in huffmanDictionary.Keys)
            {
                Console.Write("{0}:  ", c);
                foreach (int bit in huffmanDictionary[c])
                {
                    Console.Write("{0}", bit);
                }

                Console.WriteLine();
            }

            // write in file encoded text
            BytesCount = hufWrapper.WriteEncodedToFile(PathDir + "WarAndPeace1_encoded",
                                                       hufWrapper.GetEncodedText(Source, huffmanDictionary));

            //Decompress
            string      binaryString = hufWrapper.ReadBytesFromFile(PathDir + "WarAndPeace1_encoded", BytesCount);
            List <char> decodedList  = hufWrapper.Decode(binaryString);

            hufWrapper.WriteDecodedToFile(decodedList, PathDir + "WarAndPeace1_decoded.txt");
        }