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 encodedByte = encodedData[byteNum]; for (var bitNum = 0; bitNum < 8 && byteNum * 8 + bitNum < bitsCount; bitNum++) { //сдвигается предыдущее значение, считывается бит под номером bitNum из encodedByte и добавляется => собирается последовательность бит sample.Bits = (sample.Bits << 1) + ((encodedByte & (1 << (8 - bitNum - 1))) != 0 ? 1 : 0); sample.BitsCount++; byte decodedByte; if (!decodeTable.TryGetValue(sample, out 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; //берет столько битов, чтобы дополнить текущий байт var neededBits = 8 - _unfinishedBits.BitsCount; while (bitsCount >= neededBits) { bitsCount -= neededBits; //берет needBits битов, дополняет байт, записывает в буффер _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(byte[] data, out Dictionary <BitsWithLength, byte> decodeTable, out long bitsCount) { var frequences = CalcFrequencesTable(data); var root = BuildHuffmanTree(frequences); var encodeTable = new BitsWithLength[byte.MaxValue + 1]; _numberTasks = 0; _completeCreateEncodeTalbe = new ManualResetEvent(false); FillEncodeTable(root, encodeTable); _completeCreateEncodeTalbe.WaitOne(); var bitsBuffer = new BitsBuffer(); foreach (var b in data) { bitsBuffer.Add(encodeTable[b]); } decodeTable = CreateDecodeDict(encodeTable); return(bitsBuffer.ToArray(out bitsCount)); }