|
using System;
using System.Collections.Generic;
using System.Text;
namespace QiHe.CodeLib.Compress.DeflateFormat
{
public partial class HuffmanCodes
{
public int ReadLiteralOrLength(BitStream input)
{
return AlphabetHuffmanCode.ReadSymbol(input);
}
public int ReadDistance(BitStream input)
{
return DistanceHuffmanCode.ReadSymbol(input);
}
static public HuffmanCodes Decode(BitStream input)
{
int NumberOfLiteralLengthCodes = input.ReadBits(5) + 257;
int NumberOfDistanceCodes = input.ReadBits(5) + 1;
int NumberOfCodeLengthCodes = input.ReadBits(4) + 4;
int[] CodeLengths = new int[CodeLengthOrder.Length];
for (int i = 0; i < NumberOfCodeLengthCodes; i++)
{
int len = input.ReadBits(3);
CodeLengths[CodeLengthOrder[i]] = len;
}
HuffmanTree CodeLengthHuffmanCode = HuffmanTree.FromCodeLengths(CodeLengths);
int[] alphabetCodeLengths = ReadCodeLengths(input, NumberOfLiteralLengthCodes, CodeLengthHuffmanCode);
int[] distanceCodeLengths = ReadCodeLengths(input, NumberOfDistanceCodes, CodeLengthHuffmanCode);
return new HuffmanCodes(alphabetCodeLengths, distanceCodeLengths);
}
private static int[] ReadCodeLengths(BitStream input, int NumberOfLengthCodes, HuffmanTree CodeLengthHuffmanCode)
{
List<int> codeLengths = new List<int>();
int length = -1;
while (codeLengths.Count < NumberOfLengthCodes)
{
int symbol = CodeLengthHuffmanCode.ReadSymbol(input);
if (symbol >= 0 && symbol <= 15)
{
length = symbol;
codeLengths.Add(length);
}
else if (symbol == 16)
{
int times = input.ReadBits(2) + 3;
for (int t = 0; t < times; t++)
{
codeLengths.Add(length);
}
}
else if (symbol == 17)
{
int times = input.ReadBits(3) + 3;
for (int t = 0; t < times; t++)
{
codeLengths.Add(0);
}
}
else if (symbol == 18)
{
int times = input.ReadBits(7) + 11;
for (int t = 0; t < times; t++)
{
codeLengths.Add(0);
}
}
else
{
throw new Exception("Invalid code length symbol.");
}
}
return codeLengths.ToArray();
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.