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.>

