I founded following code on internet for string compression. When I compress a simple string, return value is very different.
For example, Compress("abc") returns "AwAAAB+LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee++997o7nU4n99//P1xmZAFs9s5K2smeIYCqyB8/fnwfPyKyyfT/AcJBJDUDAAAA"
Can I take simple string result.
Thanks
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;
MemoryStre开发者_如何学JAVAam 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);
}
Code you are using is intended for compress really large string. It compress source string by using GZip compression algorithm and then make it readable (or maybe usable / "passable") by using BASE64 encoding.
Base64 expand source string up to ~1.33 times large (8 bit symbol is encoded as 6 bit + 2 bit overflow for next symbol). So to make sense string have to be compressed at least to 70% from source length.
The result is expected and usual when using that encoding.
To answer your question please define what you mean by "simple string result"
sure, because the result is in base64 (see the last line in your code).
Compression doesn't always result in a smaller output for a few reasons:
- The input might be completely random, in which case most compressions will not compress anything, but still need to save the decompression "instructions". The result of compressing such data is data + instructions...bigger.
- The input has no features searched by the used compression algorithm. This is a very similar case to the previous one, except it is dependent on the compression algorithm used (in your case Gzip).
- Very small input. The smaller the input, the less chance to find compressible segments in it, so there is a big chance you'll get pseudo-random input (not random, but so small it looks random), and we go back to the first case again.
Base64 is a big point here, yes, but just don't forget these small facts about compression in general.
精彩评论