Skip to content

Instantly share code, notes, and snippets.

@nberardi
Created May 12, 2012 15:03
Show Gist options
  • Save nberardi/2667051 to your computer and use it in GitHub Desktop.
Save nberardi/2667051 to your computer and use it in GitHub Desktop.
ZLIB compression in .NET
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment