我需要压缩一个大字节数组,我已经在应用程序中使用了 Crypto++ 库,因此将压缩/解压缩部分放在同一个库中会很棒。
这个小测试按预期工作:
///
string test = "bleachbleachtestingbiatchbleach123123bleachbleachtestingb.....more";
string compress(string input)
{
string result ("");
CryptoPP::StringSource(input, true, new CryptoPP::Gzip(new CryptoPP::StringSink(result), 1));
return result;
}
string decompress(string _input)
{
string _result ("");
CryptoPP::StringSource(_input, true, new CryptoPP::Gunzip(new CryptoPP::StringSink(_result), 1));
return _result;
}
void main()
{
string compressed = compress(test);
string decompressed = decompress(compressed);
cout << "orginal size :" << test.length() << endl;
cout << "compressed size :" << compressed.length() << endl;
cout << "decompressed size :" << decompressed.length() << endl;
system("PAUSE");
}
我需要压缩这样的东西:
unsigned char long_array[194506]
{
0x00,0x00,0x02,0x00,0x00,0x04,0x00,0x00,0x00,
0x01,0x00,0x02,0x00,0x00,0x04,0x02,0x00,0x04,
0x04,0x00,0x02,0x00,0x01,0x04,0x02,0x00,0x04,
0x01,0x00,0x02,0x02,0x00,0x04,0x02,0x00,0x00,
0x03,0x00,0x02,0x00,0x00,0x04,0x01,0x00,0x04,
....
};
我尝试使用 long_array 作为 const char * 和 byte,然后将其提供给压缩函数,它似乎被压缩,但解压后的大小为 4,并且显然不完整。也许它太长了。 我如何重写这些压缩/解压缩函数以使用该字节数组? 谢谢你们。 :)
最佳答案
i tried to use the array as const char * and as byte then feed it to the compress function, it seems to be compressed but the decompressed one has a size of 4, and its clearly uncomplete.
使用备用 StringSource
构造函数,该构造函数采用 pointer and a length 。它将不受嵌入的 NULL
的影响。
CryptoPP::StringSource ss(long_array, sizeof(long_array), true,
new CryptoPP::Gzip(
new CryptoPP::StringSink(result), 1)
));
或者,您可以使用:
Gzip zipper(new StringSink(result), 1);
zipper.Put(long_array, sizeof(long_array));
zipper.MessageEnd();
Crypto++ 添加了 ArraySource
5.6。您也可以使用它(但它实际上是 StringSource
的 typedef
):
CryptoPP::ArraySource as(long_array, sizeof(long_array), true,
new CryptoPP::Gzip(
new CryptoPP::StringSink(result), 1)
));
用作 Gzip
参数的 1
是压缩级别。 1
是最低压缩率之一。您可以考虑使用 9
或 Gzip::MAX_DEFLATE_LEVEL
(即 9)。默认的 log2 窗口大小是最大大小,因此无需转动任何旋钮。
Gzip zipper(new StringSink(result), Gzip::MAX_DEFLATE_LEVEL);
您还应该命名您的声明。我见过 GCC 在使用匿名声明时生成错误代码。
最后,使用 long_array
(或类似的),因为 array
是 C++ 11 中的关键字。
关于c++ - Gzip 压缩/解压缩长字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27363756/