-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBufferedBitReader.java
More file actions
74 lines (61 loc) · 1.85 KB
/
BufferedBitReader.java
File metadata and controls
74 lines (61 loc) · 1.85 KB
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
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class BufferedBitReader {
// Note that we need to look ahead 3 bytes, because when the
// third byte is -1 (EOF indicator) then the second byte is a count
// of the number of valid bits in the first byte.
int current;
int next;
int afterNext;
int bitMask;
BufferedInputStream input;
public BufferedBitReader(String pathName) throws IOException {
input = new BufferedInputStream(new FileInputStream(pathName));
current = input.read();
if (current == -1) {
throw new EOFException("File did not have two bytes");
}
next = input.read();
if (next == -1) {
throw new EOFException("File did not have two bytes");
}
afterNext = input.read();
bitMask = 128;
}
public int readBit() throws IOException {
int returnBit;
if (afterNext == -1) {
if (next == 0){
return -1;
} else {
if ((bitMask & current) == 0){
returnBit = 0;
} else {
returnBit = 1;
}
next--;
bitMask = bitMask >> 1;
return returnBit;
}
} else {
if ((bitMask & current) == 0){
returnBit = 0;
} else{
returnBit = 1;
}
bitMask = bitMask >> 1;
if (bitMask == 0) {
bitMask = 128;
current = next;
next = afterNext;
afterNext = input.read();
}
return returnBit;
}
}
public void close() throws IOException {
input.close();
}
}