public static ZLibHeader DecodeHeader(int pCMF, int pFlag) { ZLibHeader result = new ZLibHeader(); //Ensure that parameters are bytes pCMF &= 0x0FF; pFlag &= 0x0FF; //Decode bytes result.CompressionInfo = Convert.ToByte((pCMF & 0xF0) >> 4); result.CompressionMethod = Convert.ToByte(pCMF & 0x0F); result.FCheck = Convert.ToByte(pFlag & 0x1F); result.FDict = Convert.ToBoolean(Convert.ToByte((pFlag & 0x20) >> 5)); result.FLevel = (FLevel)Convert.ToByte((pFlag & 0xC0) >> 6); result.IsSupportedZLibStream = (result.CompressionMethod == 8) && (result.CompressionInfo == 7) && (((pCMF * 256 + pFlag) % 31 == 0)) && (result.FDict == false); return(result); }
/// <summary> /// Check if the stream is in ZLib format /// </summary> /// <param name="stream">Stream to check</param> /// <returns>Returns true if stream is zlib format</returns> public static bool IsZLibStream(Stream stream) { bool bResult = false; ZLibHeader header; //check if sequence is at position 0, if not, we throw an exception if (stream.Position != 0) { throw new ArgumentOutOfRangeException("Sequence must be at position 0"); } //check if we can read two bytes that make the header if (stream.CanRead) { int CMF = stream.ReadByte(); int Flag = stream.ReadByte(); header = ZLibHeader.DecodeHeader(CMF, Flag); bResult = header.IsSupportedZLibStream; } return(bResult); }
/// <summary> /// Initialize stream header in ZLib format /// </summary> private void InitZLibHeader() { byte[] bytesHeader; //set header settings ZLibHeader header = new ZLibHeader { CompressionMethod = 8, //Deflate CompressionInfo = 7, FDict = false //No dictionary }; switch (_CompressionLevel) { case CompressionLevel.NoCompression: { header.FLevel = FLevel.Faster; break; } case CompressionLevel.Fastest: { header.FLevel = FLevel.Default; break; } case CompressionLevel.Optimal: { header.FLevel = FLevel.Optimal; break; } } bytesHeader = header.EncodeZlibHeader(); _RawStream.WriteByte(bytesHeader[0]); _RawStream.WriteByte(bytesHeader[1]); }