如何压缩C#中的数据在zlib python中解压

2024-09-24 02:27:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python zlib解压器,它采用如下默认参数,其中数据是字符串:

  import zlib
  data_decompressed = zlib.decompress(data)

但是,我不知道如何用c压缩一个字符串,然后用python解压。我已经完成了下一段代码,但当我试图解压缩'不正确的头检查'异常是trown。你知道吗

    static byte[] ZipContent(string entryName)
    {
        // remove whitespace from xml and convert to byte array
        byte[] normalBytes;
        using (StringWriter writer = new StringWriter())
        {
            //xml.Save(writer, SaveOptions.DisableFormatting);
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            normalBytes = encoding.GetBytes(writer.ToString());
        }

        // zip into new, zipped, byte array
        using (Stream memOutput = new MemoryStream())
        using (ZipOutputStream zipOutput = new ZipOutputStream(memOutput))
        {
            zipOutput.SetLevel(6);

            ZipEntry entry = new ZipEntry(entryName);
            entry.CompressionMethod = CompressionMethod.Deflated;
            entry.DateTime = DateTime.Now;
            zipOutput.PutNextEntry(entry);

            zipOutput.Write(normalBytes, 0, normalBytes.Length);
            zipOutput.Finish();

            byte[] newBytes = new byte[memOutput.Length];
            memOutput.Seek(0, SeekOrigin.Begin);
            memOutput.Read(newBytes, 0, newBytes.Length);

            zipOutput.Close();

            return newBytes;
        }
    }

有人能帮我吗? 非常感谢。你知道吗

更新1:

我已经尝试过脱脂功能,正如设拉子·贝吉(Shiraz Bhaiji)发布的:

    public static byte[] Deflate(byte[] data)
    {
        if (null == data || data.Length < 1) return null;
        byte[] compressedBytes;

        //write into a new memory stream wrapped by a deflate stream
        using (MemoryStream ms = new MemoryStream())
        {
            using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true))
            {
                //write byte buffer into memorystream
                deflateStream.Write(data, 0, data.Length);
                deflateStream.Close();

                //rewind memory stream and write to base 64 string
                compressedBytes = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(compressedBytes, 0, (int)ms.Length);

            }
        }
        return compressedBytes;
    }

问题是要在python代码中正常工作,我必须添加“-zlib.MAX\u位“要解压缩的参数如下:

    data_decompressed = zlib.decompress(data, -zlib.MAX_WBITS)

所以,我的新问题是:有没有可能在C语言中编写一个deflate方法,用哪个压缩结果可以解压zlib.减压(数据)作为默认值?你知道吗


Tags: newdatabytelengthmswriterusingentry