public
Created

ZLIB compression in .NET

  • Download Gist
zlip.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
public static byte[] ZlibCompress(byte[] data)
{
using (MemoryStream outStream = new MemoryStream())
{
// zlib header
outStream.WriteByte(0x58);
outStream.WriteByte(0x85);
 
// zlib body
using (var compressor = new DeflateStream(outStream, CompressionMode.Compress, true))
compressor.Write(data, 0, data.Length);
 
// zlib checksum - a naive implementation of adler-32 checksum
const uint A32Mod = 65521;
uint s1 = 1, s2 = 0;
foreach (byte b in data)
{
s1 = (s1 + b) % A32Mod;
s2 = (s2 + s1) % A32Mod;
}
 
int adler32 = unchecked((int)((s2 << 16) + s1));
outStream.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(adler32)), 0, sizeof(uint));
 
// zlib compatible compressed query
var bytes = outStream.ToArray();
outStream.Close();
 
return bytes;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.