You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用LZ4压缩/解压时结果与原字符串不符的问题及修正代码

解决LZ4压缩完整句子后解压结果异常的问题

我之前碰到过完全一样的状况:用LZ4压缩短字符串(比如"1234")一切正常,但处理长句子时,解压出来的内容和原始字符串完全无关。经过排查调整,终于得到了能正常工作的代码,分享给你:

int Compress(const char* source, char* dest, int sourceSize, int maxDestSize)
{
    return LZ4_compress_default(source, dest, sourceSize, maxDestSize);
}

int Decompress(const char* source, char* dest, int compressedSize, int maxDecompressedSize)
{
    return LZ4_decompress_safe(source, dest, compressedSize, maxDecompressedSize);
}

int main()
{
    char source[1024] = "Arguing that you don\'t care about the right to privacy because you have nothing to hide is no different than saying you don\'t care about free speech because you have nothing to say.";

    char buff[1024 * 4] = { 0 };
    char buff_a[1024 * 4] = { 0 };

    int x = Compress(source, buff, strlen(source), sizeof(buff));
    printf("\nBYTE COMPRESSED : %i\nDATA COMPRESSED : \n", x);
    for (int i = 0; i < x; i++)
        printf(" %2x", (unsigned)buff[i]);

    int y = Decompress(buff, buff_a, x, sizeof(buff_a));
    printf("\n\nBYTE DECOMPRESSED : %i\nDATA DECOMPRESSED : \n", y);
    for (int i = 0; i < y; i++)
        printf(" %02x", (unsigned)buff_a[i]);

    printf("\n\n\n\nEXIT\n");
    getchar();
    return 0;
}

简单说下关键调整点:

  • 确保压缩时传递的原始数据长度是准确的(这里用strlen(source)精准获取字符串长度)
  • 使用LZ4官方推荐的LZ4_compress_default和LZ4_decompress_safe函数对,这是最稳定的基础压缩/解压接口,能适配绝大多数场景
  • 解压时必须传入准确的压缩后数据长度(也就是压缩函数返回的x值),同时保证目标缓冲区足够容纳解压后的内容

运行这段代码后,你会看到解压后的字节序列和原始字符串完全一致,不会再出现内容无关的问题了。

内容的提问来源于stack exchange,提问作者Rafael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:13:28