-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRunLength.java
49 lines (46 loc) · 1.3 KB
/
RunLength.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
public class RunLength {
public static void compress() {
int count = 0;
boolean oldBit = false;
while (!BinaryStdIn.isEmpty()) {
System.err.println("ITER");
boolean bit = BinaryStdIn.readBoolean();
if (bit != oldBit) {
BinaryStdOut.write((byte) count);
oldBit = !oldBit;
count = 0;
}
if (count == 255) {
BinaryStdOut.write((byte) count);
BinaryStdOut.write((byte) 0);
count = 0;
}
count++;
}
BinaryStdOut.write((byte) count);
BinaryStdOut.flush();
BinaryStdOut.close();
}
public static void decompress() {
boolean bit = false;
while(!BinaryStdIn.isEmpty()) {
int count = BinaryStdIn.readByte() & 0xff;
for (int i = 0; i < count; i++) {
BinaryStdOut.write(bit);
}
bit = !bit;
}
BinaryStdOut.flush();
BinaryStdOut.close();
}
public static void main(String[] args) {
String option = args[0];
switch (option) {
case "+":
compress();
break;
case "-":
decompress();
}
}
}