Пример #1
0
        /// Converts the scrambled alphanumeric values provided into a bitset
        /// which will be used to parse through the Huffman Tree.
        private DAABitArray ConvertTextToBits(char[] charArray)
        {
            DAABitArray bitArray = new DAABitArray();
            int temp;
            String binary = "";
            String bitString = "";
            foreach (char c in charArray)
            {
                temp = CharToDecimal(c);
                bitString = Convert.ToString(temp, 2);

                /// Append leading 0's, removed from the ToString() function
                while (bitString.Length < 6)
                {
                    bitString = "0" + bitString;
                }
                binary += bitString;
            }

            foreach (char d in binary.ToCharArray())
            {
                if (d == '0')
                    bitArray.Append(false);
                else
                    bitArray.Append(true);
            }
            return bitArray;
        }
Пример #2
0
        //Builds a DAABitArray with the Huffman tree from the entered text.
        private bool buildStream(DAABitArray binaryStream, string input, List <HuffLeafNode> leafNodePtrs)
        {
            bool found, noSymbol, outputOnce;

            found = noSymbol = outputOnce = false;
            foreach (char ch in input) //Iterate through each symbol in entered text.
            {
                for (int i = 0; i < leafNodePtrs.Count; i++)
                {
                    if (leafNodePtrs[i].getSymbol() == ch)                            //Find the symbol that matches the char.
                    {
                        for (int ii = 0; ii < leafNodePtrs[i].huffCode.NumBits; ii++) //Add the huffman code to the binary stream one bit at a time.
                        {
                            binaryStream.Append(leafNodePtrs[i].huffCode.GetBitAsBool(ii));
                        }
                        found = true;
                    }
                }
                if (found == false && outputOnce == false && ch != '\r') //Test if symbol rxidtd in the frequency table.
                {
                    MessageBox.Show("Symbol '" + ch + "' does not exist. Please check data input.");
                    noSymbol   = true;
                    outputOnce = true; //Used to only output the above error message once.
                }
                found = false;
            }
            return(noSymbol);
        }
Пример #3
0
        //Converts binary stream to alphanumeric cipher.
        private string compress(DAABitArray binaryStream)
        {
            int             mod;
            CompressDepress compressor = new CompressDepress(); //Object to manage depression/compression.

            mod = binaryStream.NumBits % 6;                     //Test if divisible by 6.
            if (mod != 0)                                       //Pad bit stream with 0's until a multiple of 6.
            {
                for (int i = 0; i < 6 - mod; i++)
                {
                    binaryStream.Append(0);
                }
            }
            return(compressor.compress(binaryStream));
        }
Пример #4
0
 /// <summary>
 /// Event handler for when the Compress button is clicked.
 /// Uses the frequency table to build a HuffmanTree and a Dictionary of nodes
 /// then converts the symbols to DAABitArrays using the Dictionary to find the node.
 /// Also appends 0 bits to make the entire bit sequence divisable by 6.
 /// The frequency table must be the same as the one to encode it or bad things happen.
 /// </summary>
 /// <param name="sender">Event Stuff (Don't ask me, I didn't put it there?</param>
 /// <param name="e">State information</param>
 private void btnCompress_Click(object sender, RoutedEventArgs e)
 {
     //try
     {
         string[]         freqStringList = txtFreqTbl.Text.Split('\n');
         List <Frequency> frequencies    = new List <Frequency>();
         foreach (string s in freqStringList)
         {
             frequencies.Add(new Frequency(s));
         }
         Dictionary <char, HuffmanTreeNodeLeaf> dict = new Dictionary <char, HuffmanTreeNodeLeaf>();
         HuffmanTreeNodeComposite root = HuffmanTreeNode.HuffmanTreeFactory(frequencies, dict);
         DAABitArray bits      = new DAABitArray();
         string      converted = "";
         foreach (char character in txtPlain.Text)
         {
             DAABitArray append = new DAABitArray();
             bits.Append(dict[character].encode(append));
         }
         while (bits.NumBits % 6 != 0)
         {
             bits.Append(false);
         }
         int index = 0;
         while (index <= bits.NumBits - 6)
         {
             converted = converted + bits.SixToChar(index);
             index     = index + 6;
         }
         txtCompressed.Text = converted;
     }
     //catch (Exception ex)
     {
         // MessageBox.Show(ex.Message);
     }
 }
Пример #5
0
 /// <summary>
 /// Event handler for when the Compress button is clicked. 
 /// Uses the frequency table to build a HuffmanTree and a Dictionary of nodes
 /// then converts the symbols to DAABitArrays using the Dictionary to find the node.
 /// Also appends 0 bits to make the entire bit sequence divisable by 6.
 /// The frequency table must be the same as the one to encode it or bad things happen.
 /// </summary>
 /// <param name="sender">Event Stuff (Don't ask me, I didn't put it there?</param>
 /// <param name="e">State information</param>
 private void btnCompress_Click(object sender, RoutedEventArgs e)
 {
     //try
     {
         string[] freqStringList = txtFreqTbl.Text.Split('\n');
         List<Frequency> frequencies = new List<Frequency>();
         foreach (string s in freqStringList)
         {
             frequencies.Add(new Frequency(s));
         }
         Dictionary<char, HuffmanTreeNodeLeaf> dict = new Dictionary<char, HuffmanTreeNodeLeaf>();
         HuffmanTreeNodeComposite root = HuffmanTreeNode.HuffmanTreeFactory(frequencies, dict);
         DAABitArray bits = new DAABitArray();
         string converted = "";
         foreach (char character in txtPlain.Text)
         {
             DAABitArray append = new DAABitArray();
             bits.Append(dict[character].encode(append));
         }
         while (bits.NumBits % 6 != 0)
         {
             bits.Append(false);
         }
         int index = 0;
         while (index <= bits.NumBits - 6)
         {
             converted = converted + bits.SixToChar(index);
             index = index + 6;
         }
         txtCompressed.Text = converted;
     }
     //catch (Exception ex)
     {
        // MessageBox.Show(ex.Message);
     }
 }
Пример #6
0
        //Converts alphanumeric cipher to binary stream.
        public DAABitArray decompressCipher(String compressedText)
        {
            DAABitArray decompStream = new DAABitArray();

            foreach (char ch in compressedText)                //Iterate through each character of the alphanumeric code.
            {
                for (int i = 0; i < alphanumerics.Length; i++) //Find the character in the alphanumeric array.
                {
                    if (alphanumerics[i] == ch.ToString())
                    {
                        decompStream.Append(i, 6); //Add equivalent six bit code to bit stream.
                    }
                }
            }
            return(decompStream);
        }
Пример #7
0
        //Converts binary stream to uncompressed text.
        public string decompressStream(DAABitArray decompStream, List <HuffLeafNode> leafNodePtrs)
        {
            DAABitArray tempBitArray = new DAABitArray();
            string      decompString = "";

            for (int i = 0; i < decompStream.NumBits; i++)                                   //Iterate through each bit of bit stream.
            {
                tempBitArray.Append(decompStream.GetBitAsBool(i));                           //Add one bit to temp bit stream.
                for (int j = 0; j < leafNodePtrs.Count; j++)                                 //Compare temp bit stream to each leaf node of huffman tree.
                {
                    if (bitArraysEqual(tempBitArray, leafNodePtrs[j].getHashCode()) == true) //If symbol found, add character to output string.
                    {
                        tempBitArray = new DAABitArray();
                        decompString = decompString + leafNodePtrs[j].getSymbol();
                    }
                }
            }
            return(decompString);
        }
Пример #8
0
 /// <summary>
 /// Event handler for when the Decompress button is clicked.
 /// Uses the frequency table to build a HuffmanTree then uses that tree to decode the data.
 /// The frequency table must be the same as the one to encode it or bad things happen.
 /// </summary>
 /// <param name="sender">Event Stuff (Don't ask me, I didn't put it there?</param>
 /// <param name="e">State information</param>
 private void btnDecompress_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         string[]         freqStringList = txtFreqTbl.Text.Split('\n');
         List <Frequency> frequencies    = new List <Frequency>();
         foreach (string s in freqStringList)
         {
             frequencies.Add(new Frequency(s));
         }
         HuffmanTreeNodeComposite       root = HuffmanTreeNode.HuffmanTreeFactory(frequencies, new Dictionary <char, HuffmanTreeNodeLeaf>());
         Dictionary <char, DAABitArray> dict = new Dictionary <char, DAABitArray>();
         for (int ii = 0; ii < 64; ii++)
         {
             long        x    = (long)ii;
             DAABitArray bits = new DAABitArray();
             bits.Append(x, 6);
             dict.Add(DAABitArray.encoding[ii], bits);
         }
         DAABitArray encodedBits = new DAABitArray();
         foreach (char character in txtCompressed.Text)
         {
             encodedBits.Append(dict[character]);
         }
         string decoded = "";
         while (encodedBits.NumBits > 0)
         {
             decoded = decoded + root.decode(encodedBits).ToString();
         }
         txtPlain.Text = decoded;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #9
0
 /// <summary>
 /// Event handler for when the Decompress button is clicked. 
 /// Uses the frequency table to build a HuffmanTree then uses that tree to decode the data. 
 /// The frequency table must be the same as the one to encode it or bad things happen.
 /// </summary>
 /// <param name="sender">Event Stuff (Don't ask me, I didn't put it there?</param>
 /// <param name="e">State information</param>
 private void btnDecompress_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         string[] freqStringList = txtFreqTbl.Text.Split('\n');
         List<Frequency> frequencies = new List<Frequency>();
         foreach (string s in freqStringList)
         {
             frequencies.Add(new Frequency(s));
         }
         HuffmanTreeNodeComposite root = HuffmanTreeNode.HuffmanTreeFactory(frequencies, new Dictionary<char, HuffmanTreeNodeLeaf>());
         Dictionary<char, DAABitArray> dict = new Dictionary<char, DAABitArray>();
         for (int ii = 0; ii < 64; ii++)
         {
             long x = (long)ii;
             DAABitArray bits = new DAABitArray();
             bits.Append(x, 6);
             dict.Add(DAABitArray.encoding[ii], bits);
         }
         DAABitArray encodedBits = new DAABitArray();
         foreach (char character in txtCompressed.Text)
         {
             encodedBits.Append(dict[character]);
         }
         string decoded = "";
         while (encodedBits.NumBits > 0)
         {
             decoded = decoded + root.decode(encodedBits).ToString();
         }
         txtPlain.Text = decoded;
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #10
0
        private void btnCompress_Click(object sender, RoutedEventArgs e)
        {
            /*the user should type sth in the plain text*/
            if (txtPlain.Text == "" && txtFreqTbl.Text == "" || txtPlain.Text == "")
            {
                MessageBox.Show("Please type something in the plain text ");
            }

            else if (txtFreqTbl.Text == "")
            {
                MessageBox.Show("Please click the Freq calc button first ");
            }
            else
            /*start parse the input*/
            {
                int value;
                /*get the input if the user input sth form the symbol table*/
                string inFreqTbl = txtFreqTbl.Text;
                var    inDict    = new Dictionary <char, int>();
                /*remove the whitesaper at the start or end*/
                string theFreqTbl  = inFreqTbl.Trim();
                bool   formatError = false;

                /*Loops for each new line in the symbol table box*/
                foreach (string aLine in theFreqTbl.Split('\n'))
                {
                    /*use the ":" to spilt every string*/
                    string[] a = aLine.Split(':');

                    char[] key = a[0].ToCharArray();

                    /*when some incorrect type in the symbol table then show the message to user  */
                    try
                    {
                        if (key[0] == '\\')
                        {
                            key[0] = '\n';
                        }
                        int.TryParse(a[1], out value);
                        /*when the use type something in the symbol table should type a positive number and the format like a:5*/
                        double sqrt = Math.Sqrt(value);

                        if (sqrt.Equals(Double.NaN) || !int.TryParse(a[1], out value))
                        {
                            throw (new Exception("Negative frequency "));
                        }

                        /*can not input duplicate key  */
                        inDict.Add(key[0], value);
                    }

                    catch
                    {
                        MessageBox.Show("Incorrect input,can not type negative frequency or duplicate character, the format should like 'char:int'");
                        formatError = true;
                    }
                }


                if (!formatError)
                {
                    HuffmanTree tree = new HuffmanTree(inDict);


                    IDictionary <char, string> encodings = tree.CreateEncodings();

                    /* converts the characters in plain text to an array*/
                    char[] txtplain = txtPlain.Text.ToCharArray();

                    string huffstring = "";

                    string wrongSymbol = "";

                    bool error = false;

                    /*loop all the char in plaintext convert into its huffman code*/
                    foreach (char pChar in txtplain)
                    {
                        /*  Check the char in plaintext as a key in the huffman dictionary*/
                        bool correctkey = false;
                        if (encodings.ContainsKey(pChar))
                        {
                            correctkey = true;
                        }
                        else
                        /*//  the character does not have huffman code*/
                        {
                            error        = true;
                            wrongSymbol += pChar + " ";
                        }
                        if (correctkey)
                        {
                            huffstring += encodings[pChar];
                        }
                    }
                    if (error)
                    {
                        MessageBox.Show(wrongSymbol + " can not compress this character, please try another one");
                    }


                    DAABitArray newBitArray = new DAABitArray();
                    int         huffInt;

                    /*loops all bits in the huffstring to single ints that can add to the DAABitArray*/
                    foreach (char huffchar in huffstring)
                    {
                        huffInt = (int)Char.GetNumericValue(huffchar);
                        newBitArray.Append(huffInt);
                    }
                    /* Call the textInterpretation and output the result on compressed text*/
                    TextInterpretation newTextInter = new TextInterpretation();

                    txtCompressed.Text = newTextInter.Interpertation(newBitArray);
                }
            }
        }