LZW - understanding

Currently learning about LZW, and encoding / decoding in general. So for encoding Ive seen some sample programs around. The bit im trying to get some actual understand of is when you want to actually write to the compressed file.

import java.io.*;

import java.util.*;

publicclass Compress{

finalstaticint MAX_CODES = 4096;

finalstaticint BYTE_SIZE = 8;

finalstaticint EXCESS = 4;

finalstaticint ALPHA = 256;

finalstaticint MASK1 = 255;

finalstaticint MASK2 = 15;

staticint leftOver;

staticboolean bitsLeftOver;

static BufferedInputStream in;

static BufferedOutputStream out;

privatestaticvoid setFiles(String[] args)throws IOException{

String inputFile, outputFile;

if(args.length >= 1){

inputFile = args[0];

in =new BufferedInputStream(new FileInputStream(inputFile));

outputFile = inputFile+".zzz";

out =new BufferedOutputStream(new FileOutputStream(outputFile));

}

else{

System.out.print("usage:java Compress <filename>");

System.exit(1);

}

}

privatestaticvoid output(int pcode)throws IOException{

int c,d;

if(bitsLeftOver){

d = pcode & MASK1;

c = (leftOver << EXCESS)+(pcode>>BYTE_SIZE);

out.write(c);

out.write(d);

bitsLeftOver =false;

}

else{

leftOver = pcode & MASK2;

c = pcode>>EXCESS;

out.write(c);

bitsLeftOver =true;

}

}

privatestaticvoid compress()throws IOException{

Hashtable table =new Hashtable();

for(int i=0; i<ALPHA; i++)

table.put(new Integer(i),new Integer(i));

int codeUsed = ALPHA;

int c = in.read();

if(c!=-1){

int pcode = c;

c = in.read();

while(c!=-1){

int k = (pcode<<BYTE_SIZE)+c;

Integer e = (Integer)table.get(new Integer(k));

if(e==null){

output(pcode);

if(codeUsed><MAX_CODES)

table.put(new Integer((pcode><<BYTE_SIZE)+c),new Integer(codeUsed++));

pcode = c;

}

else pcode = e.intValue();

c=in.read();

}

output(pcode);

if(bitsLeftOver)

out.write(leftOver<<EXCESS);

}

in.close();

out.close();

}

publicstaticvoid main(String[] args)throws IOException{

setFiles(args);

compress();

}

}

What is going on the output method, the actual algorithm is np. But the bit shifting I cant seem to understand the logic off.>

[5753 byte] By [Lunny2006a] at [2007-11-27 2:29:22]
# 1

> What is going on the output method, the actual algorithm is np.

> But the bit shifting I cant seem to understand the logic off.

The values which are passed in to output have 12 bits which need to be output. However, it's only possible to output to a stream in 8-bit bytes. Therefore it alternates:

1. Write the top 8 bits and store the remaining 4.

2. Write the stored 4 bits with the top 4 bits of the new value, followed by the remaining 8 bits of the new value.

Confusingly the output method is written so that the code for step 2 comes before the code for step 1. I'd regard that as bad style.

YAT_Archivista at 2007-7-12 2:42:29 > top of Java-index,Java Essentials,New To Java...