代码之家  ›  专栏  ›  技术社区  ›  Radek

LZW在C中减压

  •  2
  • Radek  · 技术社区  · 15 年前

    我有一个用C语言写的LZW压缩机/减压器。

    初始表由ASCII字符组成,然后每个要保存到表中的字符串都由 前缀 和A 性格 两者都以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;
    }
    

    你能找到它吗?我会感激的。

    1 回复  |  直到 15 年前
        1
  •  4
  •   interjay    15 年前

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

    ...
    firstChar = decode(currentCode);
    dictionaryAdd(previousCode, firstChar, nextCode++);
    previousCode = currentCode;
    ...
    
    推荐文章