Exemplo n.º 1
0
        private void BuildTree()
        {
            foreach (KeyValuePair <char, int> symbol in _frequencies)
            {
                nodes.Add(new HuffmanTreeNode()
                {
                    Symbol = symbol.Key, Frequency = symbol.Value
                });
            }

            while (nodes.Count > 1)
            {
                List <HuffmanTreeNode> orderedNodes = nodes.OrderBy(node => node.Frequency).ToList();

                if (orderedNodes.Count >= 2)
                {
                    HuffmanTreeNode parent = new HuffmanTreeNode()
                    {
                        Symbol    = '*',
                        Frequency = orderedNodes[0].Frequency + orderedNodes[1].Frequency,
                        Left      = orderedNodes[0],
                        Right     = orderedNodes[1]
                    };

                    nodes.Remove(orderedNodes[0]);
                    nodes.Remove(orderedNodes[1]);
                    nodes.Add(parent);
                }

                Root = nodes.FirstOrDefault();
            }
        }
Exemplo n.º 2
0
        public byte[] Decode(byte[] data)
        {
            HuffmanTreeNode current = Root;

            _scratch     = new byte[data.Length];
            _bitPosition = 0;
            int bytePosition = 0;

            int lenght = data.Length * 8;

            while (_bitPosition < lenght)
            {
                bool bit = data.ReadBit(_bitPosition, 0);
                _bitPosition++;
                if (bit)
                {
                    if (current.Right != null)
                    {
                        current = current.Right;
                    }
                }
                else
                {
                    if (current.Left != null)
                    {
                        current = current.Left;
                    }
                }

                if (current.IsLeaf())
                {
                    if (current.Symbol == EOD)
                    {
                        break;
                    }
                    _scratch = _scratch.WriteByte(bytePosition, (byte)current.Symbol);
                    bytePosition++;
                    current = Root;
                }
            }

            byte[] decompressedData = new byte[bytePosition];
            Array.Copy(_scratch, decompressedData, bytePosition);
            _scratch = null;

            return(decompressedData);
        }