2009-12-02 66 views
1

我有一个LZW压缩器/解压缩器中C.LZW减压用C

初始表包括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; 
} 

你能发现它吗?我会很感激。

+1

请注意,你应该尽量避免依赖你的压缩,直到你可以解压缩它。换句话说,如果你的陈述“我的压缩工作”实际上意味着“它减少了你的大小”,就是这样,你不应该排除该代码中的一个错误。 – 2009-12-02 15:03:09

+3

我的压缩在我的输入作品中使用别人的解压缩。 – Radek 2009-12-02 15:04:27

+1

第8行 - > previousCode = input [0];似乎对我很可疑。你在decode()中调用appendCharacter()来输出,但是这个第一个代码永远不会呈现给appendCharacter()来输出。另外,如果inputSize为零,则输入[0]可能是一个糟糕的解引用。 – meklarian 2009-12-02 15:19:05

回答

4

你的解码函数返回字符串中的第一个字符。你需要这个角色,以便将它添加到字典中,但你应该设置previousCode它。所以你的代码应该看起来像:

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

完美interjay,我现在明白为什么我做到了!对你好的业力:) – Radek 2009-12-02 15:26:48