简单的Zlib C ++字符串压缩和解压缩

时间:2014-12-17 15:54:00

标签: c++ boost zlib

我需要在C ++中对std :: string进行简单的压缩和解压缩。我查看了这个site,代码是针对Character数组的。我想要实现的是两个功能:

std::string original = "This is to be compressed!!!!";
std::string compressed = string_compress(original);
std::cout << compressed << std::endl;
std::string decompressed = string_decompress(compressed);
std::cout << decompressed << std::endl;

我曾尝试过将压缩压缩为:

std::string CompressData(const std::string &data)
{
    std::stringstream compressed;
    std::stringstream decompressed;
    decompressed << data;
    boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
    out.push(boost::iostreams::zlib_compressor());
    out.push(decompressed);
    boost::iostreams::copy(out, compressed);
    return compressed.str();
}

std::string DecompressData(const std::string &data)
{
    std::stringstream compressed;
    std::stringstream decompressed;
    compressed << data;
    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
    in.push(boost::iostreams::zlib_decompressor());
    in.push(compressed);
    boost::iostreams::copy(in, decompressed);
    return decompressed.str();
}

但代码有时会在字符串中给出Null字符,即 \ u0000 。如果压缩数据包含这些空字符,我该如何处理。返回类型字符串是否正确?如何使用zlib实现函数 string_compress string_decompress

2 个答案:

答案 0 :(得分:6)

你可以像@LawfulEvil那样建议。这是有效的代码片段:)

std::string original = "This is to be compressed!!!!";
std::string compressed_encoded = string_compress_encode(original);
std::cout << compressed_encoded << std::endl;
std::string decompressed_decoded = string_decompress_decode(compressed_encoded);
std::cout << decompressed_decoded << std::endl;

使用this作为base64编码/解码库

std::string string_compress_encode(const std::string &data)
{
    std::stringstream compressed;
    std::stringstream original;
    original << data;
    boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
    out.push(boost::iostreams::zlib_compressor());
    out.push(original);
    boost::iostreams::copy(out, compressed);

    /**need to encode here **/
    std::string compressed_encoded = base64_encode(reinterpret_cast<const unsigned char*>(compressed.c_str()), compressed.length());

    return compressed_encoded.str();
}

std::string string_decompress_decode(const std::string &data)
{
    std::stringstream compressed_encoded;
    std::stringstream decompressed;
    compressed_encoded << data;

    /** first decode  then decompress **/
    std::string compressed = base64_decode(compressed_encoded);

    boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
    in.push(boost::iostreams::zlib_decompressor());
    in.push(compressed);
    boost::iostreams::copy(in, decompressed);
    return decompressed;
}

答案 1 :(得分:1)

压缩使用每个字节可用的所有值,因此在尝试查看为ascii时,它将显示为“垃圾”或“怪异”字符。它的预期。您需要对传输/ json打包的数据进行编码以避免空值。我建议基础64.这样做的代码可以在下面的链接中找到(我没有创作,所以我不会在这里复制)。

  1. http://www.adp-gmbh.ch/cpp/common/base64.html
  2. Binary data JSONCPP