public static byte[] Decode(byte[] encodedData, Dictionary <BitsWithLength, byte> decodeTable, long bitsCount) { var result = new List <byte>(); var sample = new BitsWithLength { Bits = 0, BitsCount = 0 }; for (var byteNum = 0; byteNum < encodedData.Length; byteNum++) { var b = encodedData[byteNum]; for (var bitNum = 0; bitNum < 8 && byteNum * 8 + bitNum < bitsCount; bitNum++) { sample.Bits = (sample.Bits << 1) + ((b & (1 << (8 - bitNum - 1))) != 0 ? 1 : 0); sample.BitsCount++; if (!decodeTable.TryGetValue(sample, out var decodedByte)) { continue; } result.Add(decodedByte); sample.BitsCount = 0; sample.Bits = 0; } } return(result.ToArray()); }
public void Add(BitsWithLength bitsWithLength) { var bitsCount = bitsWithLength.BitsCount; var bits = bitsWithLength.Bits; int neededBits = 8 - unfinishedBits.BitsCount; while (bitsCount >= neededBits) { bitsCount -= neededBits; buffer.Add((byte) ((unfinishedBits.Bits << neededBits) + (bits >> bitsCount))); bits = bits & ((1 << bitsCount) - 1); unfinishedBits.Bits = 0; unfinishedBits.BitsCount = 0; neededBits = 8; } unfinishedBits.BitsCount += bitsCount; unfinishedBits.Bits = (unfinishedBits.Bits << bitsCount) + bits; }
public static byte[] Encode(List <byte> data, out Dictionary <BitsWithLength, byte> decodeTable, out long bitsCount) { var frequences = CalcFrequences(data); var root = BuildHuffmanTree(frequences); var encodeTable = new BitsWithLength[byte.MaxValue + 1]; FillEncodeTable(root, encodeTable); var bitsBuffer = new BitsBuffer(); foreach (var b in data) { bitsBuffer.Add(encodeTable[b]); } decodeTable = CreateDecodeTable(encodeTable); return(bitsBuffer.ToArray(out bitsCount)); }