GZipStream:为什么我们在压缩后转换为base 64? [英] GZipStream: why do we convert to base 64 after compression?

查看:211
本文介绍了GZipStream:为什么我们在压缩后转换为base 64?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是看一个用于压缩字符串的代码示例。我发现使用GZipStream类足够了。但我不明白为什么我们必须将其转换为base 64字符串,如示例所示。

I was just looking at a code sample for compressing a string. I find that using the GZipStream class suffices. But I don't understand why we have to convert it to base 64 string 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);
}



此外,我不明白我的gzBuffer初始化为大小 compressed.Length + 4 。其实我不明白为什么我们有最后几个语句。有人可以分享一些光...

Further, I don't understand my the gzBuffer is initialized to a size compressed.Length + 4. Actually i don't understand why we have the last few statements either. Can someone share some light...

PS:我不是计算机科学学生。

PS: I'm not a computer science student.

推荐答案

很可能base 64字符串是可以看作是纯文本,例如打印,包括在电子邮件或类似的东西。 修改:现在我看到了 source ,他们说他们想要将它插入一个XML文件,这就是为什么他们需要是纯文本。

Most likely the base 64 string is so that it can be viewed as plain text, for example for printing, including in an email or something like that. Now I see the source, they say they want to insert it in an XML file, so that is why they needed to be plain text.

compressed.Length + 4 大小是必需的,因为下一行 - BlockCopy 。它开始从4个字节复制到gzBuffer。 (第四个参数是到目标缓冲区的字节偏移量)。第二个BlockCopy将压缩字符串的长度放入目标缓冲区的前四个字节。我不知道为什么它需要这里的长度,但可能有一个相应的解码程序它必须排队。

The compressed.Length + 4 size is required because of the next line - BlockCopy. It starts copying from 4 bytes into the gzBuffer. (The 4th argument is the byte offset into the destination buffer). The second BlockCopy is putting the length of the compressed string into the first four bytes of the destination buffer. I'm not sure why it would need the length here, but there may well be a corresponding decode routine it has to line up with.

编辑: / strong>该长度用于解压缩例程,以便程序知道解压缩的字节缓冲区应该有多长时间。

The length is used in the decompression routine so that the program knows how long the decompressed byte buffer should be.

这篇关于GZipStream:为什么我们在压缩后转换为base 64?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆