Game Development Reference
In-Depth Information
The gzip algorithm is a lossless data format that is safe from patents. The gzip
implementation provided by Microsoft is completely compatible with the unix
gzip functionality, though the .NET implementation has a slightly weaker com-
pression algorithm. The gzip implementation follows the format from RFC 1952.
Microsoft .NET 2.0 provides gzip functionality through the GZipStream class.
Another great feature of the gzip format is that there is a cyclic redundancy check-
sum that is used to detect data corruption.
The GZipStream class cannot be used to compress files larger than four gigabytes in size.
Implementation for Arbitrary Data
The first step to use the GZipStream class is to include the appropriate namespaces.
using System;
using System.IO;
using System.IO.Compression;
The following method is used to compress arbitrary data stored in a byte array and
return a byte array containing the compressed data. Notice that the input data
length is written as the first four bytes of the stream. This is so the decompression
method can decompress that data without having to determine the original file
size of the data. This was done to improve performance and speed, sacrificing
compatibility with other gzip implementations. We want to know the original size
of the data before compression so we can allocate enough memory to store the
data after decompression.
Data is compressed on the fly as it is written into the GZipStream . Notice that the
constructor for GZipStream references the memory stream that will hold the resul-
tant data. This compression can be done against any stream object, including,
FileStream for files.
internal static byte[] CompressData(byte[] input)
using (MemoryStream output = new MemoryStream())
output.Write(BitConverter.GetBytes(input.Length), 0, 4);
Search Nedrilad ::

Custom Search