c - C 中的 LZW 解压

标签 c compression lzw localized

我有一个用 C 编写的 LZW 压缩器/解压缩器。

初始表由 ASCII 字符组成,然后要保存到表中的每个现在字符串由一个前缀和一个字符组成,两者均以 int 形式保存在列表中。

我的压缩有效,但解压时遗漏了一些字符。

输入:

<title>Agile</title><body><h1>Agile</h1></body></html>

我得到的输出(注意缺少“e”和“<”):

<title>Agile</title><body><h1>Agil</h1></body>/html>

这是我使用的代码(相关部分):

void expand(int * input, int inputSize) {    
    // int prevcode, currcode
    int previousCode; int currentCode;
    int nextCode = 256; // start with the same dictionary of 255 characters
    dictionaryInit();

    // prevcode = read in a code
    previousCode = input[0];

    int pointer = 1;

    // while (there is still data to read)
    while (pointer < inputSize) {
        // currcode = read in a code
        currentCode = input[pointer++];

        if (currentCode >= nextCode) printf("!"); // XXX not yet implemented!
        currentCode = decode(currentCode);

        // add a new code to the string table
        dictionaryAdd(previousCode, currentCode, nextCode++);

        // prevcode = currcode
        previousCode = currentCode;
    }
}

int decode(int code) {
    int character; int temp;

    if (code > 255) { // decode
        character = dictionaryCharacter(code);
        temp = decode(dictionaryPrefix(code)); // recursion
    } else {
        character = code; // ASCII
        temp = code;
    }
    appendCharacter(character); // save to output
    return temp;
}

你能发现吗?我将不胜感激。

最佳答案

您的解码函数返回字符串中的第一个字符。您需要此字符才能将其添加到字典中,但您不应该为其设置 previousCode。所以你的代码应该如下所示:

...
firstChar = decode(currentCode);
dictionaryAdd(previousCode, firstChar, nextCode++);
previousCode = currentCode;
...

关于c - C 中的 LZW 解压,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1833437/

相关文章:

javascript - 在通过套接字发送到客户端之前压缩中等大小的 JavaScript 数组是否值得?

java - LZW 编码器解码器 - 符号表

将设置_与地址连接

c++ - Lua C API : Retrieve values from Lua function returning a table in C code

c - if 语句后的 Printf 命令不起作用

c - 高速字符检测 rs232

c# - 如何在不使用第三方 dll 的情况下使用 dotnet framework 4.0 提取 zip 文件

docker - 如何在 docker 容器中压缩文件?

Javascript - 用于数据库条目的 lzw 压缩的替代方案

python-2.7 - 压缩什么时候会增加文件大小?