Esempio n. 1
0
        Codeword NextCodeword(Codeword codeword, uint suffixBit)
        {
            var c = Codeword.Clone(codeword);

            c.AppendBit(suffixBit);
            return(c);
        }
Esempio n. 2
0
        // turn the codewords into canonical ordered ones
        // needed for make table later
        void MakeCanonical(List <Node> leaves1)
        {
            // see https://pineight.com/mw/index.php?title=Canonical_Huffman_code
            // http://www.compressconsult.com/huffman
            // https://en.wikipedia.org/wiki/Canonical_Huffman_code

            // sort by bit lengths to order symbol values.
            // on ties, sort by symbol
            leaves1.Sort((a, b) =>
            {
                int result = a.Codeword.BitLength.CompareTo(b.Codeword.BitLength);
                if (result == 0)
                {
                    return(a.Symbol.CompareTo(b.Symbol));
                }
                return(result);
            });

            // rewrite symbols in increasing order, maintaining code lengths
            if (Options.HasFlag(OptionFlags.DumpDictionary))
            {
                WriteLine("Huffman dictionary: ");
            }
            var codeValue = new Codeword();

            codeValue.AppendBit(0); // start at the 1-bit code of 0
            foreach (var leaf in leaves1)
            {
                // lengthen code
                while (codeValue.BitLength < leaf.Codeword.BitLength)
                {
                    codeValue.AppendBit(0);
                }
                leaf.Codeword = Codeword.Clone(codeValue);
                if (Options.HasFlag(OptionFlags.DumpDictionary))
                {
                    WriteLine($"  x{leaf.Symbol:X2}->{leaf.Codeword}");
                }
                codeValue.Increment();
            }
        }