代码之家  ›  专栏  ›  技术社区  ›  Alex

如何确定字符串的大小并对其进行压缩

  •  6
  • Alex  · 技术社区  · 14 年前

    我目前正在用C语言开发一个应用程序,它使用 Amazon SQS 消息的大小限制为8KB。

    我的方法是:

    public void QueueMessage(string message)
    

    在这个方法中,我首先要压缩消息(大多数消息作为JSON传入,所以已经相当小了)

    如果压缩字符串仍然大于8KB,我将把它存储在S3中。

    我的问题是:

    如何轻松测试字符串的大小,压缩它的最佳方法是什么? 我不是在寻找大规模的规模削减,只是一些美好和容易-和容易减压的另一端。

    2 回复  |  直到 12 年前
        1
  •  12
  •   Marc Gravell    14 年前

    要知道字符串的“大小”(以KB为单位),我们需要知道编码。如果我们假设为utf8,那么它(不包括bom等)如下(如果不是utf8,则交换编码):

    int len = Encoding.UTF8.GetByteCount(longString);
    

    重新打包;我建议gzip使用utf8,如果必须是字符串,可以选择后跟base-64:

        using (MemoryStream ms = new MemoryStream())
        {
            using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
            {
                byte[] raw = Encoding.UTF8.GetBytes(longString);
                gzip.Write(raw, 0, raw.Length);
                gzip.Close();
            }
            byte[] zipped = ms.ToArray(); // as a BLOB
            string base64 = Convert.ToBase64String(zipped); // as a string
            // store zipped or base64
        }
    
        2
  •  1
  •   nitin kumar    12 年前

    给这个函数解压字节。我能想到的最好方法是

    public static byte[] ZipToUnzipBytes(byte[] bytesContext)
            {
                byte[] arrUnZipFile = null;
                if (bytesContext.Length > 100)
                {
                    using (var inFile = new MemoryStream(bytesContext))
                    {
                        using (var decompress = new GZipStream(inFile, CompressionMode.Decompress, false))
                        {
                            byte[] bufferWrite = new byte[4];
                            inFile.Position = (int)inFile.Length - 4;
                            inFile.Read(bufferWrite, 0, 4);
                            inFile.Position = 0;
                            arrUnZipFile = new byte[BitConverter.ToInt32(bufferWrite, 0) + 100];
                            decompress.Read(arrUnZipFile, 0, arrUnZipFile.Length);
                        }
                    }
                }
                return arrUnZipFile;
            }