gpt4 book ai didi

c++ - Boost gzip如何将压缩字符串输出为文本

转载 作者:行者123 更新时间:2023-12-02 18:23:00 53 4
gpt4 key购买 nike

我正在使用 boost gzip 示例 code这里。我正在尝试压缩一个简单的字符串 test 并期待压缩字符串 H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA 如此在线 compressor 中所示

static std::string compress(const std::string& data)
{
namespace bio = boost::iostreams;
std::stringstream compressed;
std::stringstream origin(data);

bio::filtering_streambuf<bio::input> out;
out.push(bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
out.push(origin);

bio::copy(out, compressed);
return compressed.str();
}

int main(int argc, char* argv[]){
std::cout << compress("text") << std::endl;
// prints out garabage

return 0;
}

然而,当我打印出转换结果时,我得到了像 +I- 这样的垃圾值。 ~

我知道这是一个有效的转换,因为解压值返回了正确的字符串。但是我需要字符串的格式是人类可读的,即 H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA

如何修改代码以输出人类可读的文本?

谢谢

动机

垃圾格式与我将通过其发送压缩文本的 JSON 库不兼容。

最佳答案

示例站点完全没有提到他们也对结果进行了 base64 编码:

base64 -d <<< 'H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA' | gunzip -

Prints :

test

简而言之,您还需要这样做:

Live On Coliru

#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <iostream>
#include <sstream>

#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>

std::string decode64(std::string const& val)
{
using namespace boost::archive::iterators;
return {
transform_width<binary_from_base64<std::string::const_iterator>, 8, 6>{
std::begin(val)},
{std::end(val)},
};
}

std::string encode64(std::string const& val)
{
using namespace boost::archive::iterators;
std::string r{
base64_from_binary<transform_width<std::string::const_iterator, 6, 8>>{
std::begin(val)},
{std::end(val)},
};
return r.append((3 - val.size() % 3) % 3, '=');
}

static std::string compress(const std::string& data)
{
namespace bio = boost::iostreams;
std::istringstream origin(data);

bio::filtering_istreambuf in;
in.push(
bio::gzip_compressor(bio::gzip_params(bio::gzip::best_compression)));
in.push(origin);

std::ostringstream compressed;
bio::copy(in, compressed);
return compressed.str();
}

static std::string decompress(const std::string& data)
{
namespace bio = boost::iostreams;
std::istringstream compressed(data);

bio::filtering_istreambuf in;
in.push(bio::gzip_decompressor());
in.push(compressed);

std::ostringstream origin;
bio::copy(in, origin);
return origin.str();
}

int main() {
auto msg = encode64(compress("test"));
std::cout << msg << std::endl;
std::cout << decompress(decode64(msg)) << std::endl;
}

打印

H4sIAAAAAAAC/ytJLS4BAAx+f9gEAAAA
test

关于c++ - Boost gzip如何将压缩字符串输出为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70624519/

53 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com