Esempio n. 1
0
        public static BitList MakeTableBinary(byte[] buf, out Dictionary <byte, BitList> table)
        {
            // Make Huffman Tree
            var nodemap = Collection.Seq(256).Select(a => new ValueCount {
                Value = (byte)a, Count = 0,
            }).ToDictionary(a => a.Value);

            for (var i = 0; i < buf.Length; i++)
            {
                nodemap[buf[i]].Count++;
            }
            var htree = new HuffmanTree(nodemap.Values.Where(a => a.Count > 0))
                        .Build();

            table = new Dictionary <byte, BitList>();
            foreach (ValueCount vc in htree)
            {
                table[vc.Value] = htree.GetBitResult(vc);
            }

            var ret = new BitList();

            ret.Add((UInt16)table.Count);   // [TA] TABLE COUNT (16bits) / < 32767 = Count
            foreach (var kv in table)
            {
                ret.Add(kv.Key);   // [TB] VALUE (8bits)
                var lenbits = BitList.MakeVariableBits((UInt64)kv.Value.Count);
                ret.Add(lenbits);  // [TC] LENGTH OF BITPATTERN
                ret.Add(kv.Value); // [TE] BIT Pattern (n bits)
            }
            ret.AddPad();          // [TF] padding

            return(ret);
        }
Esempio n. 2
0
        public override byte[] Compress(byte[] buf)
        {
            var ret = MakeTableBinary(TableID, Table, out var table);

            // ADD DATA FIELDS
            ret.Add(BitList.MakeVariableBits((UInt64)buf.Length));  // [DA] Data Bytes
            foreach (var c in buf)
            {
                ret.Add(table[c]);                    // [DB] Huffman code
                if (ret.ByteCount >= LimitSize)
                {
                    return(null);
                }
            }
            ret.AddPad();                             // [DC] padding

            return(ret.ToByteArray());
        }