The LZW compression algorithm is increasing the size in bits after compression:
Here is the code for Compression function:
// 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();
}
Where the writeBinary (It acts like a buffer in the program) function is as follows:
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);
}
}
Can you spot the error, please? I'll be grateful!