forked from dancollins/comp317_lzw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnpacker.java
112 lines (101 loc) · 2.57 KB
/
Unpacker.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/**
* Bit Unpacker
*
* Take an input stream of bytes (binary) and decompress it by extracting
* integers and outputting them in ASCII on a line.
*
* Dan Collins 2014
* 1183446
*/
import java.io.IOException;
class Unpacker {
/**
* Calculate the number of bits needed to represent a number.
* @param The value to test
* @returns The minimum number of bits needed to represent the value
*
* @link http://stackoverflow.com/a/680040
*/
public static int log2(int v) {
return Integer.SIZE - Integer.numberOfLeadingZeros(v);
}
public static void main(String[] args) {
int maxPhrase = 255;
int maxBits = 20;
// Read args
// -b Maximum bits per phrase
// NOTE: This is Severin's code
if (args.length == 2){
if (args[0].equals("-b")){
try {
maxBits = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println("An integer must follow -b");
return;
}
} else {
System.err.println("The only valid argument is -b");
return;
}
} else if (args.length != 0){
System.err.println("The only valid argument is -b maxnumbits");
return;
}
// Input data
int inByte = 0;
// Intermediate step
int inBytePiece = 0;
int phraseBits = 0;
int inBits = 0;
// Output data
int phraseNumber = 0;
try {
do {
// If we're at the start of a new phrase, prepare to read the
// bits
if (phraseBits == 0) {
phraseBits = log2(maxPhrase);
phraseBits = phraseBits > maxBits ? maxBits : phraseBits;
}
// If we have bits from the last in byte, OR them into the
// phrase
if (inBits > 0) {
if (phraseBits < inBits) {
// Get the bits to save, and prepare inByte for the next
// loop.
inBytePiece = inByte >> (8 - phraseBits);
inByte &= (int)(Math.pow(2, 8 - phraseBits) - 1);
// Load the bits into the output phrase
phraseNumber <<= phraseBits;
phraseNumber |= inBytePiece;
// Set up for the next read
inBits -= phraseBits;
phraseBits = 0;
} else {
// Load the read bits into the output phrase
phraseNumber <<= inBits;
phraseNumber |= inByte;
// Set up for the next read
phraseBits -= inBits;
inBits = 0;
}
}
if (phraseBits == 0) {
// Output the phrase
System.out.println(phraseNumber);
phraseNumber = 0;
maxPhrase += 1;
}
if (inBits == 0) {
// Read the next byte
inByte = System.in.read();
inBits = 8;
}
} while (inByte != -1);
} catch (IOException e) {
System.err.println("Failed to read from input stream!");
e.printStackTrace();
return;
}
}
}