📄 huffdecoder.java
字号:
/****************************HuffDecoder classused to decoded a Huffman encoded Bitstream ****************************/package huffmancoding;import java.io.*;import java.util.Arrays;import java.util.HashMap;public class HuffDecoder{ private final int BYTE_LENGTH = 8; private final int DWORD_LENGTH = 32; // used to normalize the byte range (-128 to 127) to array indicies private final int BYTE_RANGE = Byte.MAX_VALUE + Math.abs(Byte.MIN_VALUE) + 1; // sentinel values for huffman header private final byte SENTINEL_BYTE = 65; private final int SENTINEL_FREQ = 0; private Bitstream decodedStream; public HuffDecoder(Bitstream inputStream) { inputStream.reset(); int numCodes = inputStream.readDWord(); // get the freqs from the file int[] frequencies = getFreqs(inputStream); System.out.println("got freqs"); // build a decoder tree from the freqs HuffTree decoderTree = new HuffTree(frequencies); System.out.println("Decoder: got tree"); // decode the stream decodedStream = decodeStream(inputStream, decoderTree, numCodes); System.out.println("Decoder: got decoded stream"); } // returns the decoded stream public Bitstream getDecodedStream() { return decodedStream; } // pulls the frequency table from the file header private int[] getFreqs(Bitstream stream) { int[] freqs = new int[BYTE_RANGE]; Arrays.fill(freqs, 0); byte theByte = stream.readByte(); int theFreq = stream.readDWord(); // pull freq info until we hit the sentinel value while( (theByte != SENTINEL_BYTE || theFreq != SENTINEL_FREQ) && !stream.eof()) { freqs[theByte - Byte.MIN_VALUE] = theFreq; theByte = stream.readByte(); theFreq = stream.readDWord(); System.out.println(theByte + " - " + theFreq); } return freqs; } // decodes the stream and returns it private Bitstream decodeStream(Bitstream inStream, HuffTree decoderTree, int numCodes) { decodedStream = new Bitstream(); for (int codeIterator = 0; codeIterator < numCodes; codeIterator++) { decodedStream.writeByte(decoderTree.getByte(inStream)); } decodedStream.reset(); return decodedStream; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -