首页
学习
活动
专区
圈层
工具
发布

LZW压缩
EN

Stack Overflow用户
提问于 2017-05-18 10:27:26
回答 1查看 913关注 0票数 0

LZW压缩算法在压缩后增加以位为单位的大小:

以下是Compression函数的代码:

代码语言:javascript
复制
// compression
void compress(FILE *inputFile, FILE *outputFile) {    
    int prefix;
    int character;

    int nextCode;
    int index;

    // LZW starts out with a dictionary of 256 characters (in the case of 8 codeLength) and uses those as the "standard"
    //  character set.
    nextCode = 256; // next code is the next available string code
    dictionaryInit();

    // while (there is still data to be read)
    while ((character = getc(inputFile)) != (unsigned)EOF) { // ch = read a character;

        // if (dictionary contains prefix+character)
        if ((index = dictionaryLookup(prefix, character)) != -1) prefix = index; // prefix = prefix+character
        else { // ...no, try to add it
            // encode s to output file
            writeBinary(outputFile, prefix);

            // add prefix+character to dictionary
            if (nextCode < dictionarySize) dictionaryAdd(prefix, character, nextCode++);

            // prefix = character
            prefix = character; //... output the last string after adding the new one
        }
    }
    // encode s to output file
    writeBinary(outputFile, prefix); // output the last code

    if (leftover > 0) fputc(leftoverBits << 4, outputFile);

    // free the dictionary here
    dictionaryDestroy();
}

其中writeBinary (它的作用类似于程序中的缓冲区)函数如下:

代码语言:javascript
复制
void writeBinary(FILE * output, int code);

int leftover = 0;
int leftoverBits;

    void writeBinary(FILE * output, int code) {
        if (leftover > 0) {
            int previousCode = (leftoverBits << 4) + (code >> 8);

            fputc(previousCode, output);
            fputc(code, output);

            leftover = 0; // no leftover now
        } else {
            leftoverBits = code & 0xF; // save leftover, the last 00001111
            leftover = 1;

            fputc(code >> 4, output);
        }
    }

你能找出错误吗?我会很感激的!

EN

回答 1

Stack Overflow用户

发布于 2017-08-06 01:39:57

chux已经向您指出了解决方案:您需要从9位代码开始,并在当前位大小的可用代码耗尽时将代码大小增加到12。如果您从一开始就编写12位代码,那么当然没有压缩效果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44037600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档