dmolony-DiskBrowser/src/com/bytezone/diskbrowser/wizardry/Huffman.java

71 lines
1.8 KiB
Java
Raw Normal View History

2016-08-16 06:34:23 +00:00
package com.bytezone.diskbrowser.wizardry;
2016-08-16 22:55:51 +00:00
// Based on a pascal routine by Tom Ewers
2016-08-16 06:34:23 +00:00
public class Huffman
{
private final byte[] tree;
private final byte[] left;
private final byte[] right;
2016-08-16 22:55:51 +00:00
private int bitNo;
private int msgPtr;
private int currentByte;
2016-08-16 06:34:23 +00:00
private byte[] message;
public Huffman (byte[] buffer)
{
tree = new byte[256];
left = new byte[256];
right = new byte[256];
System.arraycopy (buffer, 0, tree, 0, 256);
System.arraycopy (buffer, 256, left, 0, 256);
System.arraycopy (buffer, 512, right, 0, 256);
}
public String getMessage (byte[] message)
{
this.message = message;
2016-08-16 09:04:17 +00:00
bitNo = 0;
2016-08-16 06:34:23 +00:00
msgPtr = 0;
2016-08-16 09:04:17 +00:00
currentByte = 0;
2016-08-16 06:34:23 +00:00
int len = getChar ();
StringBuilder text = new StringBuilder ();
for (int i = 0; i < len; i++)
text.append ((char) getChar ());
2016-08-16 22:55:51 +00:00
2016-08-16 06:34:23 +00:00
return text.toString ();
}
private byte getChar ()
{
2016-08-16 22:55:51 +00:00
int treePtr = 0; // start at the root
2016-08-16 06:34:23 +00:00
while (true)
{
2016-08-16 22:55:51 +00:00
if (bitNo-- == 0)
2016-08-16 06:34:23 +00:00
{
2016-08-16 22:55:51 +00:00
bitNo = 7;
2016-08-16 09:04:17 +00:00
currentByte = message[msgPtr++] & 0xFF;
2016-08-16 06:34:23 +00:00
}
2016-08-16 22:55:51 +00:00
int currentBit = currentByte % 2; // get the next bit to process
2016-08-16 09:04:17 +00:00
currentByte /= 2;
2016-08-16 06:34:23 +00:00
2016-08-16 09:04:17 +00:00
if (currentBit == 0) // take right path
2016-08-16 06:34:23 +00:00
{
2016-08-16 09:04:17 +00:00
if ((tree[treePtr] & 0x02) != 0) // if has right leaf...
return right[treePtr]; // return that character
treePtr = right[treePtr] & 0xFF; // else go to right node
2016-08-16 06:34:23 +00:00
}
else // take left path
{
2016-08-16 09:04:17 +00:00
if ((tree[treePtr] & 0x01) != 0) // if has left leaf...
return left[treePtr]; // return that character
treePtr = left[treePtr] & 0xFF; // else go to left node
2016-08-16 06:34:23 +00:00
}
}
}
}