GZipStream:为什么我们转换后的COM pression立足64?COM、GZipStream、pression

2023-09-03 20:52:36 作者:兜兜里有根棒棒糖︶ε╰

我只是在寻找的COM pressing字符串中的code样本。我发现,使用的GZipStream类足够了。但我不明白为什么我们把它转换为基础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初始化为大小 COM pressed.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.

推荐答案

最有可能的基地64字符串,以便它可以被看作是纯文本,例如打印,包括在一封电子邮件中或类似的东西。 修改现在我看到的来源,他们说他们想将其插入一个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.

COM pressed.Length + 4 尺寸是必需的 - 的 BlockCopy 。它从4个字节到gzBuffer复制。 (第四个参数是字节偏移到目标缓冲区)。第二BlockCopy是把COM pressed字符串的长度进前四个字节目标缓冲区。我不知道为什么它会需要的长度在这里,但也有可能是它有排队了相应的去code程序。

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.

编辑:的长度是用在DECOM pression程序,使程序知道pssed DECOM $ P $字节的缓冲区应该有多长。

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