Esempio n. 1
0
        private static Dictionary <int, Dictionary <int, byte> > BuildOptmizedTable(HuffmanDecodingData huffmanData)
        {
            var returned = new Dictionary <int, Dictionary <int, byte> >();

            foreach (var entry in huffmanData.Table)
            {
                if (!returned.ContainsKey(entry.Value.NbBits))
                {
                    returned.Add(entry.Value.NbBits, new Dictionary <int, byte>());
                }

                returned[entry.Value.NbBits].Add(entry.Value.EncodedValue, entry.Key);
            }

            return(returned);
        }
Esempio n. 2
0
        private static void WriteCompressedFiles
        (
            string outputFile,
            string outputTableFile,
            byte[] bytes,
            Dictionary <byte, HuffmanTableEntry> huffmanBinaryTable
        )
        {
            int toWrite = 0;
            int nbBits  = 0;

            int nbBitsTotal = 0;

            FileStream fs = File.Create(outputFile);

            foreach (var b in bytes)
            {
                var entry = huffmanBinaryTable[b];
                toWrite = toWrite << entry.NbBits;
                toWrite = toWrite + entry.EncodedValue;

                nbBits      += entry.NbBits;
                nbBitsTotal += entry.NbBits;
                if (nbBits >= NB_BITS_PACKED)
                {
                    var        copy         = toWrite;
                    int        deltaShift   = nbBits - NB_BITS_PACKED;
                    BigInteger shiftBack    = copy >> deltaShift;
                    var        bytesToWrite = shiftBack.ToByteArray();
                    fs.Write(bytesToWrite, 0, 1);
                    int mask = 0;
                    for (int i = 0; i < deltaShift; i++)
                    {
                        mask = mask << 1;
                        mask = mask + 1;
                    }
                    toWrite = toWrite & mask;
                    nbBits  = nbBits - NB_BITS_PACKED;
                }
            }

            if (nbBits > 0)
            {
                var shift = NB_BITS_PACKED - nbBits;
                toWrite = toWrite << shift;
                var bytesToWrite = (new BigInteger(toWrite)).ToByteArray();
                fs.Write(bytesToWrite, 0, 1);
            }

            fs.Flush();
            fs.Close();

            HuffmanDecodingData data = new HuffmanDecodingData()
            {
                NbElements = bytes.Length,
                Table      = huffmanBinaryTable
            };

            var jsonString = JsonConvert.SerializeObject(data, Formatting.Indented);

            File.WriteAllText(outputTableFile, jsonString);
        }