GZipStream: why do we convert to base 64 after compression?

I was just looking at sample code for string compression. I believe that using the GZipStream class is enough. But I do not understand why we should convert it to a base 64 line, as shown in the example.

using System.IO.Compression; using System.Text; using System.IO; public static string Compress(string text) { byte[] buffer = Encoding.UTF8.GetBytes(text); MemoryStream ms = new MemoryStream(); using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) { zip.Write(buffer, 0, buffer.Length); } ms.Position = 0; MemoryStream outStream = new MemoryStream(); byte[] compressed = new byte[ms.Length]; ms.Read(compressed, 0, compressed.Length); byte[] gzBuffer = new byte[compressed.Length + 4]; System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length); System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4); return Convert.ToBase64String (gzBuffer); } 

Also, I don’t understand that gzBuffer is initialized with compressed.Length + 4 size. Actually, I don’t understand why we have the last few statements. Can someone tell a little light ...

PS: I'm not a computer science student.

+3
base64 compression gzipstream
Jul 12 '10 at 9:10
source share
1 answer

Most likely, the basic 64-line so that it can be considered as plain text, for example, for printing, including in an email or something like that. Edit: Now I see the source , they say they want to insert it into the XML file, so this is why they should be plain text.

The compressed.Length + 4 size is required due to the next line - BlockCopy . It starts copying with 4 bytes in gzBuffer. (The 4th argument is the byte offset to the destination buffer). The second BlockCopy places the length of the compressed string in the first four bytes of the destination buffer. I am not sure why length is needed here, but there may well be an appropriate decoding procedure with which it must conform.

Edit: Length is used in the decompression routine, so the program knows how long the decompressed byte buffer should be.

+3
Jul 12 '10 at 9:18
source share
β€” -



All Articles