public DeclaredSymbolInfo GetDeclaredSymbolInfo( Huffman huffman, IList<AssemblyInfo> assemblies, IList<string> projects) { var result = new DeclaredSymbolInfo { AssemblyNumber = AssemblyNumber, Glyph = Glyph, Name = Name }; if (assemblies != null && AssemblyNumber < assemblies.Count) { var assembly = assemblies[AssemblyNumber]; result.AssemblyName = assembly.AssemblyName; if (projects != null && assembly.ProjectKey >= 0 && assembly.ProjectKey < projects.Count) { result.ProjectFilePath = projects[assembly.ProjectKey]; } } result.ID = ID; result.Kind = GetKind(Glyph); if (huffman != null && Description != IntPtr.Zero) { result.Description = huffman.Uncompress(Description); } return result; }
public List<String> crearHuffman(string linea) { var huffman = new Huffman<char>(linea); List<String> lista = new List<string>(); String aux; //Codificamos List<int> codificar = huffman.listaCodificada(linea); //Decodificamos //List<char> decodificar = huffman.listaDecodificada(codificar); //var outString = new string(decodificar.ToArray()); //Console.WriteLine(outString == linea ? "Funciono" : "Fallo"); //Console.WriteLine(outString); var chars = new HashSet<char>(linea); foreach (char c in chars) { codificar = huffman.Codificador(c); //Console.Write("{0}: ", c); aux = c.ToString(); foreach (int bit in codificar) { aux = aux + bit.ToString(); //Console.Write("{0}", bit); } //Console.WriteLine(); lista.Add(aux); } //Console.ReadKey(); return lista; }
int Fixed() { int result; fixed(short *p = perserveData) { short * lencnt = p; short * lensym = lencnt + MAXBITS + 1; short * distcnt = lensym + FIXLCODES; short * distsym = distcnt + MAXBITS + 1; Huffman lencode = new Huffman { count = lencnt, symbol = lensym }; Huffman distcode = new Huffman { count = distcnt, symbol = distsym }; /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin != 0) { int symbol; short *lengths = stackalloc short[FIXLCODES]; /* literal/length table */ for (symbol = 0; symbol < 144; symbol++) { lengths[symbol] = 8; } for (; symbol < 256; symbol++) { lengths[symbol] = 9; } for (; symbol < 280; symbol++) { lengths[symbol] = 7; } for (; symbol < FIXLCODES; symbol++) { lengths[symbol] = 8; } Construct(&lencode, lengths, FIXLCODES); /* distance table */ for (symbol = 0; symbol < MAXDCODES; symbol++) { lengths[symbol] = 5; } Construct(&distcode, lengths, MAXDCODES); /* do this just once */ virgin = 0; } /* Decode data until end-of-block code */ result = Codes(&lencode, &distcode); } return(result); }
protected override void AfterStartup() { base.AfterStartup(); _lines = new List <Entity>(); _treeElements = new List <KeyValuePair <string, Entity> >(); _huffman = new Huffman(); }
public void Coef1() { var coefs = Huffman.GetCoefs("AAABBC", 5); Assert.AreEqual(Math.Round(3.0 / 6.0, 5), coefs['A']); Assert.AreEqual(Math.Round(2.0 / 6.0, 5), coefs['B']); Assert.AreEqual(Math.Round(1.0 / 6.0, 5), coefs['C']); }
public static void Main(string[] args) { Huffman ObjSym = new Huffman <int>(); //All other methods are here ObjSym.huffman_node_processing(); //this for adding the two minimum nodes ObjSym.GenerateCode(ObjSym.root, ""); //this for encoding }
public void Binary_NoSymbols_ReturnEmpty() { var huffman = new Huffman(2); var codes = huffman.GetCodes(new Dictionary <string, double>()); Assert.Empty(codes); }
public static IList <byte> Huffman(HuffmanResult huffmanResult) { var huf = new Huffman(); huf.BuildCodes(huffmanResult.BytesCounts); var hufResult = huf.Decode(huffmanResult.Bits); return(hufResult); }
private void ComputeHuffmanCodes() { byte[] array = new byte[0x1c7]; byte[] buffer2 = new byte[0x13]; uint num = this.Receive(5) + 0x101; uint num2 = this.Receive(5) + 1; uint num3 = this.Receive(4) + 4; for (int i = 0; i < num3; i++) { buffer2[LengthDezigzag[i]] = (byte) this.Receive(3); } Huffman z = new Huffman(new ArraySegment<byte>(buffer2)); int num5 = 0; while (num5 < (num + num2)) { int num6 = this.HuffmanDecode(z); if (num6 < 0x10) { array[num5++] = (byte) num6; } else { if (num6 == 0x10) { num6 = ((int) this.Receive(2)) + 3; for (int k = 0; k < num6; k++) { array[num5 + k] = array[num5 - 1]; } num5 += num6; continue; } if (num6 == 0x11) { num6 = ((int) this.Receive(3)) + 3; for (int m = 0; m < num6; m++) { array[num5 + m] = 0; } num5 += num6; continue; } num6 = ((int) this.Receive(7)) + 11; for (int j = 0; j < num6; j++) { array[num5 + j] = 0; } num5 += num6; } } if (num5 != (num + num2)) { throw new Exception("bad codelengths"); } this.Length = new Huffman(new ArraySegment<byte>(array, 0, (int) num)); this.Distance = new Huffman(new ArraySegment<byte>(array, (int) num, (int) num2)); }
private void TestHuffmanRoundtrip(string word, params string[] words) { var huffman = Huffman.Create(words); byte[] bytes = huffman.Compress(word); string actual = huffman.Uncompress(bytes); Assert.AreEqual(word, actual); }
public Client(App core, string hostname, int port) { this.core = core; this.huffman = new Huffman(); this.protocols = new Protocols(this); this.login = new Login(this); this.hostname = hostname; this.port = port; }
public void Coef0() { var coefs = Huffman.GetCoefs("ABCACDGDGG", 5); Assert.AreEqual(Math.Round(2.0 / 10.0, 5), coefs['A']); Assert.AreEqual(Math.Round(1.0 / 10.0, 5), coefs['B']); Assert.AreEqual(Math.Round(2.0 / 10.0, 5), coefs['C']); Assert.AreEqual(Math.Round(2.0 / 10.0, 5), coefs['D']); Assert.AreEqual(Math.Round(3.0 / 10.0, 5), coefs['G']); }
public void Binary_OneSymbol_ReturnCode() { var huffman = new Huffman(2); var codes = huffman.GetCodes(new Dictionary <string, double> { { "A", 1 } }); Assert.Equal(1, codes["A"].Length); }
public void HuffmanDecoding_InvalidEncoding_Throws() { foreach (byte[] encoded in InvalidEncodingData()) { // Worst case decoding is an output byte per 5 input bits, so make the decoded buffer 2 times as big byte[] decoded = new byte[encoded.Length * 2]; Assert.Throws <HuffmanDecodingException>(() => Huffman.Decode(encoded, ref decoded)); } }
public IEnumerable <Datos> Get() { var folderName = Path.Combine("Resources", "Files"); var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName); Huffman arch = new Huffman(); arch.Lista(pathToSave); return(arch.dat); }
public void Execute0() { #region Init var coefs = Huffman.GetCoefs("ABCACDGDGG", 5); var result = Huffman.Execute(coefs, 5); #endregion #region Bytes var bytes = result.Bytes; var bytes3 = bytes[3]; StringSameBytes("0", bytes3[0]); StringSameBytes("1", bytes3[1]); var bytes2 = bytes[2]; StringSameBytes("1", bytes2[0]); StringSameBytes("00", bytes2[1]); StringSameBytes("01", bytes2[2]); var bytes1 = bytes[1]; StringSameBytes("00", bytes1[0]); StringSameBytes("01", bytes1[1]); StringSameBytes("10", bytes1[2]); StringSameBytes("11", bytes1[3]); var bytes0 = bytes[0]; StringSameBytes("00", bytes0[0]); StringSameBytes("10", bytes0[1]); StringSameBytes("11", bytes0[2]); StringSameBytes("010", bytes0[3]); StringSameBytes("011", bytes0[4]); #endregion #region Bytes.Length Assert.AreEqual(4, bytes.Length); #endregion #region Bytes[i].Length Assert.AreEqual(2, bytes3.Length); Assert.AreEqual(3, bytes2.Length); Assert.AreEqual(4, bytes1.Length); Assert.AreEqual(5, bytes0.Length); #endregion }
static void Main(string[] args) { Huffman huff = new Huffman(); for (int i = 1; i < 6; i++) { huff.compressFile("data/input_assign03_0" + i + ".txt"); huff.clear(); } Console.ReadKey(); }
public FileResult Obtener(string nombre) { var direccion = "getdoc/" + nombre; var res = Data.Instancia.GuatChatService.cliente.GetAsync(direccion); res.Wait(); var result = res.Result; if (result.StatusCode == HttpStatusCode.OK) { var readTask = result.Content.ReadAsStringAsync(); readTask.Wait(); var documento = JsonConvert.DeserializeObject <Doc>(readTask.Result); var texto = Encoding.UTF8.GetBytes(documento.Contenido); var path = Server.MapPath("~/MisArchivos/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } using (var file = new FileStream(path + documento.DocName + ".sdes", FileMode.Create)) { using (var writer = new BinaryWriter(file, Encoding.UTF8)) { writer.Write(texto); } } var RutaAbsolutaServer = path; var RutaAbsolutaArchivo = RutaAbsolutaServer + documento.DocName + ".sdes"; var nombreDoc = documento.DocName + ".sdes"; var sdes = new SDES(nombreDoc, RutaAbsolutaArchivo, RutaAbsolutaServer, 250); sdes.Operar(2); var huff = new Huffman(); huff.NombreArchivoOriginal = documento.DocName + ".huff"; huff.RutaAbosolutaServer = RutaAbsolutaServer; huff.RutaAbsolutaArchivoOriginal = RutaAbsolutaServer + documento.DocName + ".huff"; huff.Descomprimir(); var fileS = new FileStream(RutaAbsolutaServer + documento.DocName + ".txt", FileMode.Open, FileAccess.Read); return(File(fileS, "*.txt", documento.DocName + ".txt")); } return(null); }
static void Main(string[] args) { Huffman Procesar = new Huffman(); string cadena = "ddabdccedchafbadgdcgabgccddbcdgg"; string cadena_cifrada = Procesar.Cifrado(cadena); string cadena_descifrada = Procesar.Descifrado(cadena_cifrada); Console.ReadLine(); }
private String GenerarCodigoHuffman(String palabra) { Huffman huffman = new Huffman(palabra); List <Arbol> lstCaracteresContados = huffman.CuentaCaracteres(huffman.InsertarCaracteresPalabra()); List <Arbol> arbolJuntado = huffman.JuntaNodo(lstCaracteresContados); huffman.EncontrarCaminoCaracteres(arbolJuntado.First().raiz, ""); return(huffman.Convertir(huffman.caminos) + huffman.ConvertPalabraASCII()); }
public void ShouldThrowErrorIfPaddingIsZero() { var buffer = new Buffer(); buffer.WriteByte(0x86); // AB = 100001 1011101 = 1000 0110 1110 1 buffer.WriteByte(0xE8); var ex = Assert.Throws <Exception>(() => { Huffman.Decode(buffer.View, bufPool); }); Assert.Equal("Invalid padding", ex.Message); }
public void Ternary_ThreeSymbols_ReturnShortestCodes() { var huffman = new Huffman(3); var codes = huffman.GetCodes(new Dictionary <string, double> { { "A", 1 }, { "B", 0.5 }, { "C", 0.5 } }); Assert.Equal(1, codes["A"].Length); Assert.Equal(1, codes["B"].Length); Assert.Equal(1, codes["C"].Length); }
// GET: Huffman public ActionResult Index() { List <HuffmanNode> ListaNodos = new List <HuffmanNode>(); ListaNodos = ObtenerLista(); Huffman compresionHuffman = new Huffman(); //compresionHuffman.GenerarArbol(ListaNodos); return(View(db.historialCompresiones.ToList())); }
public byte[] CheckTGLP(Stream input) { using (var br = new BinaryReaderX(input, true)) { if (_usesGlgr) { var compSize = br.ReadInt32(); var t = Huffman.Decompress(new MemoryStream(br.ReadBytes(compSize)), 8, 0); return(t); } return(br.ReadBytes(tglp.sheet_size)); } }
private void butEncode_Click(object sender, EventArgs e) { int accuracy = (int)numericUpDownAccuracy.Value; var coefs = Huffman.GetCoefs(fieldEncodingText.Text, accuracy); if (coefs.Count <= 1) { return; } var table = Huffman.Execute(coefs, accuracy); new ShowTable(table, coefs, accuracy).ShowDialog(); }
public void TestHuffmanRoundtripOnIndexExhaustive() { var words = GetWords(); var huffman = Huffman.Create(words); int i = 0; foreach (var word in words) { byte[] bytes = huffman.Compress(word); string actual = huffman.Uncompress(bytes); Assert.AreEqual(word, actual); i++; } }
public void Nary_NotEnoughSymbols_FillsWithGarbage(int n, int inputSize, int outputSize) { var symbols = new Dictionary <string, double>(); for (int i = 0; i < inputSize; ++i) { symbols[i.ToString()] = 1; } var huffman = new Huffman(n); var codes = huffman.GetCodes(symbols); Assert.Equal(outputSize, codes.Count); }
public static HuffmanResult Huffman(IList <byte> bytes) { var huf = new Huffman(); huf.CountBytes(bytes); huf.BuildCodes(); var hufResult = huf.Encode(bytes); var result = new HuffmanResult( bytesCounts: huf.Counts, bits: hufResult); return(result); }
public void HuffmanCompressUncompressTest() { var ThisEncoding = Encoding.UTF8; var DataString1 = "Hola. Esto es una prueba para ver si funciona la compresión Huffman."; var DataBytes1 = ThisEncoding.GetBytes(DataString1); var DataStream = new MemoryStream(DataBytes1); var UsageTable = Huffman.CalculateUsageTable(DataBytes1); var EncodingTable = Huffman.BuildTable(UsageTable); var DataBytes2 = Huffman.Uncompress(Huffman.Compress(DataStream, EncodingTable), (uint)DataBytes1.Length, EncodingTable).ReadAll(); var DataString2 = ThisEncoding.GetString(DataBytes2); Assert.AreEqual(DataString1, DataString2); }
static void Main(string[] args) { var iterations = args.Length > 0 ? int.Parse(args[0]) : 1; var bm = new Benchmark(iterations); var initState = File.ReadAllText("benchmarks/huffman_coding/lines.txt"); bm.Run(() => { Huffman huffman = new Huffman(initState); string encodedString = huffman.Encode(initState); return(encodedString.Length); }, (res) => { System.Console.WriteLine(res); }); }
/************************************************************************* * Initialize an adaptive huffman table *************************************************************************/ internal void InitializeAH(int iNSymbols) { if (iNSymbols > 255 || iNSymbols <= 0) { throw new ArgumentOutOfRangeException("iNSymbols", "iNSymbols = " + iNSymbols); } this.m_iNSymbols = iNSymbols; m_pDelta = null; m_iDiscriminant = m_iUpperBound = m_iLowerBound = 0; m_pHuffman = new Huffman(); }
public static void ReadDeclaredSymbols( string rootPath, List <IndexEntry> symbols, List <AssemblyInfo> assemblies, List <string> projects, ref Huffman huffman, ref double progress) { var masterIndexFile = Path.Combine(rootPath, "DeclaredSymbols.txt"); var huffmanFile = Path.Combine(rootPath, "Huffman.txt"); if (!File.Exists(masterIndexFile) || !File.Exists(huffmanFile)) { return; } using (Measure.Time("Read huffman tables")) { huffman = Huffman.Read(huffmanFile); } using (Measure.Time("Read binary file")) { symbols.Clear(); using (var fileStream = new FileStream( masterIndexFile, FileMode.Open, FileAccess.Read, FileShare.None, 262144, FileOptions.SequentialScan)) using (var reader = new BinaryReader(fileStream)) { int count = reader.ReadInt32(); int onePercent = Math.Max(count / 100, 1); symbols.Capacity = count; for (int i = 0; i < count; i++) { if (i % onePercent == 0) { progress = (double)i / count; } var symbol = Serialization.ReadDeclaredSymbol(reader); symbols.Add(symbol); } } } }
public void Test(IEnumerable <KeyValuePair <string, string> > input, string pattern, params string[] expectedResults) { using (var index = new Index()) { var huffman = Huffman.Create(input.Select(kvp => kvp.Value)); index.indexFinishedPopulating = true; index.huffman = huffman; index.symbols = new List <IndexEntry>(input.Select(kvp => new IndexEntry(kvp.Key, huffman.CompressToNative(kvp.Value)))); var query = index.Get(pattern); var resultSymbols = query.ResultSymbols; Assert.IsNotNull(resultSymbols); var actualResults = resultSymbols.Select(i => i.Description); Assert.IsTrue(actualResults.SequenceEqual(expectedResults)); } }
public static void ReadDeclaredSymbols( string rootPath, List<IndexEntry> symbols, List<AssemblyInfo> assemblies, List<string> projects, ref Huffman huffman, ref double progress) { var masterIndexFile = Path.Combine(rootPath, "DeclaredSymbols.txt"); if (!File.Exists(masterIndexFile)) { return; } using (Measure.Time("Read huffman tables")) { var huffmanFile = Path.Combine(rootPath, "Huffman.txt"); huffman = Huffman.Read(huffmanFile); } using (Measure.Time("Read binary file")) { symbols.Clear(); using (var fileStream = new FileStream( masterIndexFile, FileMode.Open, FileAccess.Read, FileShare.None, 262144, FileOptions.SequentialScan)) using (var reader = new BinaryReader(fileStream)) { int count = reader.ReadInt32(); int onePercent = Math.Max(count / 100, 1); symbols.Capacity = count; for (int i = 0; i < count; i++) { if (i % onePercent == 0) { progress = (double)i / count; } var symbol = Serialization.ReadDeclaredSymbol(reader); symbols.Add(symbol); } } } }
private YCbCrImage ycbcrImage; // YCrCb #endregion Fields #region Constructors public JpegDecoderCore() { huff = new Huffman[maxTc + 1, maxTh + 1]; quant = new Block[maxTq + 1]; tmp = new byte[2*Block.blockSize]; comp = new Component[maxComponents]; progCoeffs = new Block[maxComponents][]; bits = new BitsClass(); bytes = new BytesClass(); for (int i = 0; i < maxTc + 1; i++){ for (int j = 0; j < maxTh + 1; j++){ huff[i, j] = new Huffman(); } } for (int i = 0; i < quant.Length; i++){ quant[i] = new Block(); } for (int i = 0; i < comp.Length; i++){ comp[i] = new Component(); } }
public static void WriteDeclaredSymbol(BinaryWriter writer, DeclaredSymbolInfo symbol, Huffman huffman) { Write7BitEncodedInt(writer, symbol.AssemblyNumber); writer.Write(symbol.Name); writer.Write(symbol.ID); WriteBytes(writer, huffman.Compress(symbol.Description)); Write7BitEncodedInt(writer, symbol.Glyph); }
public void Dispose() { if (huffman == null || symbols == null || assemblies == null || projects == null) { return; } for (int i = 0; i < this.symbols.Count; i++) { if (this.symbols[i].Description != IntPtr.Zero) { Marshal.FreeHGlobal(this.symbols[i].Description); } } this.huffman = null; this.symbols = null; this.assemblies = null; this.projects = null; }
internal void ClearAll() { assemblies.Clear(); projects.Clear(); symbols.Clear(); guids.Clear(); projectToAssemblyIndexMap.Clear(); msbuildProperties.Clear(); msbuildItems.Clear(); msbuildTargets.Clear(); indexFinishedPopulating = false; progress = 0.0; huffman = null; }
/* * Given a list of repeated code lengths rep[0..n-1], where each byte is a * count (high four bits + 1) and a code length (low four bits), generate the * list of code lengths. This compaction reduces the size of the object code. * Then given the list of code lengths length[0..n-1] representing a canonical * Huffman code for n symbols, construct the tables required to decode those * codes. Those tables are the number of codes of each length, and the symbols * sorted by length, retaining their original order within each length. The * return value is zero for a complete code set, negative for an over- * subscribed code set, and positive for an incomplete code set. The tables * can be used if the return value is zero or positive, but they cannot be used * if the return value is negative. If the return value is zero, it is not * possible for decode() using that table to return an error--any stream of * enough bits will resolve to a symbol. If the return value is positive, then * it is possible for decode() using that table to return an error for received * codes past the end of the incomplete lengths. */ private static int Construct(ref Huffman h, byte[] rep) { int symbol; /* current symbol when stepping through length[] */ int len; /* current length when stepping through h->count[] */ int left; /* number of possible codes left of current length */ var offs = new short[MaxBits + 1]; /* offsets in symbol table for each length */ var length = new short[256]; /* code lengths */ int repPos = 0; /* convert compact repeat counts into symbol bit length list */ symbol = 0; while (repPos < rep.Length) { len = rep[repPos++]; left = (len >> 4) + 1; len &= 15; do { length[symbol++] = (short)len; } while (--left > 0); } int n = symbol; /* count number of codes of each length */ for (len = 0; len <= MaxBits; len++) h.Count[len] = 0; for (symbol = 0; symbol < n; symbol++) (h.Count[length[symbol]])++; /* assumes lengths are within bounds */ if (h.Count[0] == n) /* no codes! */ return 0; /* complete, but decode() will fail */ /* check for an over-subscribed or incomplete set of lengths */ left = 1; /* one possible code of zero length */ for (len = 1; len <= MaxBits; len++) { left <<= 1; /* one more bit, double codes left */ left -= h.Count[len]; /* deduct count from possible codes */ if (left < 0) return left; /* over-subscribed--return negative */ } /* left > 0 means incomplete */ /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MaxBits; len++) offs[len + 1] = (short)(offs[len] + h.Count[len]); /* * put symbols in table sorted by length, by symbol order within each * length */ for (symbol = 0; symbol < n; symbol++) if (length[symbol] != 0) h.Symbol[offs[length[symbol]]++] = (short)symbol; /* return zero for complete set, positive for incomplete set */ return left; }
private byte DecodeHuffman(Huffman h) { if (h.nCodes == 0){ throw new Exception("uninitialized Huffman table"); } if (bits.n < 8){ try{ EnsureNBits(8); } catch (MissingFF00Exception){ if (bytes.nUnreadable != 0){ UnreadByteStuffedByte(); } goto slowPath; } catch (ShortHuffmanDataException){ if (bytes.nUnreadable != 0){ UnreadByteStuffedByte(); } goto slowPath; } } ushort v = h.lut[(bits.a >> (bits.n - lutSize)) & 0xff]; if (v != 0){ byte n = (byte) ((v & 0xff) - 1); bits.n -= n; bits.m >>= n; return (byte) (v >> 8); } slowPath: int code = 0; for (int i = 0; i < maxCodeLength; i++){ if (bits.n == 0){ EnsureNBits(1); } if ((bits.a & bits.m) != 0){ code |= 1; } bits.n--; bits.m >>= 1; if (code <= h.maxCodes[i]){ return h.vals[h.valsIndices[i] + code - h.minCodes[i]]; } code <<= 1; } throw new Exception("bad Huffman code"); }
private void Refine(Block b, Huffman h, int zigStart, int zigEnd, int delta) { if (zigStart == 0){ if (zigEnd != 0){ throw new Exception("Invalid state for zig DC component"); } bool bit = DecodeBit(); if (bit){ b[0] |= delta; } return; } int zig = zigStart; if (eobRun == 0){ for (; zig <= zigEnd; zig++){ bool done = false; int z = 0; var val = DecodeHuffman(h); int val0 = val >> 4; int val1 = val & 0x0f; switch (val1){ case 0: if (val0 != 0x0f){ eobRun = (ushort) (1 << val0); if (val0 != 0){ uint bits = DecodeBits(val0); eobRun |= (ushort) bits; } done = true; } break; case 1: z = delta; bool bit = DecodeBit(); if (!bit){ z = -z; } break; default: throw new Exception("unexpected Huffman code"); } if (done){ break; } zig = RefineNonZeroes(b, zig, zigEnd, val0, delta); if (zig > zigEnd){ throw new Exception($"too many coefficients {zig} > {zigEnd}"); } if (z != 0){ b[unzig[zig]] = z; } } } if (eobRun > 0){ eobRun--; RefineNonZeroes(b, zig, zigEnd, -1, delta); } }
/* * Decode a code from the stream s using huffman table h. Return the symbol or * a negative value if there is an error. If all of the lengths are zero, i.e. * an empty code, or if the code is incomplete and an invalid code is received, * then -9 is returned after reading MAXBITS bits. * * Format notes: * * - The codes as stored in the compressed data are bit-reversed relative to * a simple integer ordering of codes of the same lengths. Hence below the * bits are pulled from the compressed data one at a time and used to * build the code value reversed from what is in the stream in order to * permit simple integer comparisons for decoding. * * - The first code for the shortest length is all ones. Subsequent codes of * the same length are simply integer decrements of the previous code. When * moving up a length, a one bit is appended to the code. For a complete * code, the last code of the longest length will be all zeros. To support * this ordering, the bits pulled during decoding are inverted to apply the * more "natural" ordering starting with all zeros and incrementing. */ private int Decode(ref Huffman h) { int len = 1; // current number of bits in code int code = 0; // len bits being decoded int first = 0; // first code of length len int index = 0; // index of first code of length len in symbol table int bits = bitBuf; // bits from stream int left = bitCount; // bits left in next or left to process int next = 1; // index into next number of codes while (true) { while (left-- > 0) { code |= (bits & 1) ^ 1; // invert code bits >>= 1; int count = h.Count[next++]; // number of codes of length len if (code < first + count) { // if length len, return symbol bitBuf = bits; bitCount = (bitCount - len) & 7; return h.Symbol[index + (code - first)]; } index += count; // else update for next length first += count; first <<= 1; code <<= 1; len++; } left = (MaxBits + 1) - len; if (left == 0) break; bits = inBuf[inPos++]; if (left > 8) left = 8; } return -9; /* ran out of codes */ }
private int HuffmanDecode(Huffman z) { int num; if (this.NumBits < 0x10) { this.FillBits(); } int index = z.Fast[(int) ((IntPtr) (this.CodeBuffer & 0x1ff))]; if (index < 0xffff) { num = z.Size[index]; this.CodeBuffer = this.CodeBuffer >> num; this.NumBits -= num; return z.Value[index]; } int num3 = BitReverse((int) this.CodeBuffer, 0x10); num = 10; while (true) { if (num3 < z.MaxCode[num]) { break; } num++; } if (num == 0x10) { return -1; } index = ((num3 >> (0x10 - num)) - z.FirstCode[num]) + z.FirstSymbol[num]; this.CodeBuffer = this.CodeBuffer >> num; this.NumBits -= num; return z.Value[index]; }
private List<byte> Inflate() { bool flag; this.Out = new List<byte>(); this.NumBits = 0; this.CodeBuffer = 0; Label_0019: flag = this.Receive(1) != 0; switch (((int) this.Receive(2))) { case 0: this.ParseUncompressedBlock(); goto Label_00A6; case 3: throw new Exception("invalid block type"); case 1: if (DefaultDistance[0x1f] == 0) { InitDefaults(); } this.Length = new Huffman(new ArraySegment<byte>(DefaultLength)); this.Distance = new Huffman(new ArraySegment<byte>(DefaultDistance)); break; default: this.ComputeHuffmanCodes(); break; } this.ParseHuffmanBlock(); Label_00A6: if (!flag) { goto Label_0019; } return this.Out; }
/************************************************************************* Initialize an adaptive huffman table *************************************************************************/ internal void InitializeAH(int iNSymbols) { if (iNSymbols > 255 || iNSymbols <= 0) { throw new ArgumentOutOfRangeException("iNSymbols", "iNSymbols = " + iNSymbols); } m_iNSymbols = iNSymbols; m_pDelta = null; m_iDiscriminant = m_iUpperBound = m_iLowerBound = 0; m_pHuffman = new Huffman(); }
protected string Encrypt() { var plainText = _builder.ToString(); string encrypted = RijndaelSimple.Encrypt(plainText, Passphrase, SaltValue, "SHA1", 1, InitVector, 256); string log; Huffman h = new Huffman(plainText); var hash = h.Encode(out log); string e = string.Empty; foreach (var b in hash) { e += b.ToString("x2").ToLower(); } return "r4dio:" + TrackSource + ":" + e; }