zoukankan      html  css  js  c++  java
  • 使用gzip压缩字符串

    虽然对简单的字符串效率不高,但是对长的字符串还是可以的。

        static string CompressString(string input)
            {
                string retValue = string.Empty;
                if (!string.IsNullOrEmpty(input))
                {
                    byte[] byteSource = Encoding.UTF8.GetBytes(input);
                    MemoryStream msm = new MemoryStream();
                    using (GZipStream gzs = new GZipStream(msm, CompressionMode.Compress, true))
                    {
                        gzs.Write(byteSource, 0, byteSource.Length);
                    }
    
                    msm.Position = 0;
    
                    byte[] compBytes = new byte[msm.Length];
                    msm.Read(compBytes, 0, compBytes.Length);
    
                    msm.Close();
    
                    byte[] finalBuffer = new byte[compBytes.Length + 4];
                    Buffer.BlockCopy(compBytes, 0, finalBuffer, 4, compBytes.Length);
                    Buffer.BlockCopy(BitConverter.GetBytes(byteSource.Length), 0, finalBuffer, 0, 4);
    
                    retValue = System.Convert.ToBase64String(finalBuffer);
                }
    
                return retValue;
            }
    
            static string DecompressString(string input)
            {
                string retValue = string.Empty;
                if (!string.IsNullOrEmpty(input))
                {
                    byte[] source = System.Convert.FromBase64String(input);
                    using (MemoryStream msm = new MemoryStream())
                    {
                        int length = BitConverter.ToInt32(source, 0);
                        msm.Write(source, 4, source.Length - 4);
    
                        //Console.WriteLine(Encoding.UTF8.GetString(source));
    
                        msm.Position = 0;
                        byte[] decmpBytes = new byte[length];
                        using (GZipStream gzs = new GZipStream(msm, CompressionMode.Decompress))
                        {
                            gzs.Read(decmpBytes, 0, length);
    
                            //gzs.CopyTo();
                        }
    
                        retValue = Encoding.UTF8.GetString(decmpBytes);
                    }
                }
    
                return retValue;
            }
  • 相关阅读:
    javascript运动详解
    jQuery Ajax封装通用类 (linjq)
    Bootstrap 字体图标引用示例
    jQuery $.each用法
    jquery中odd和even选择器的用法说明
    JQuery中怎么设置class
    HTML5中input背景提示文字(placeholder)的CSS美化
    边框上下左右各部位隐藏显示详解
    纯CSS气泡框实现方法探究
    对比Tornado和Twisted两种异步Python框架
  • 原文地址:https://www.cnblogs.com/fgynew/p/1934917.html
Copyright © 2011-2022 走看看