-
Notifications
You must be signed in to change notification settings - Fork 0
/
BufferedBitReader.java
97 lines (78 loc) · 2.42 KB
/
BufferedBitReader.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
import java.io.*;
/**
* Reads bits from a file, one at a time.
* Assumes that the last byte of the file contains the number of
* valid bits in the previous byte.
*
* @author Scot Drysdale
*/
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; // Current byte being returned, bit by bit
int next; // Next byte to be returned (could be a count)
int afterNext; // Byte two after the current byte
int bitMask; // Shows which bit to return
BufferedInputStream input;
/**
* Constructor
* @param pathName the path name of the file to open
* @throws IOException
*/
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; // a 1 in leftmost bit position
}
/**
* Reads a bit and returns it as a 0 or a 1.
* Returns -1 when all bits have been returned
*
* @return the bit read (0 or 1)
* @throws IOException
*/
public int readBit() throws IOException {
int returnBit; // Hold the bit to return
if(afterNext == -1) // Are we emptying the last byte?
// When afterNext == -1, next is the count of bits remaining.
if(next == 0) // No more bits in the final byte to return
return -1; // No more bits to return
else {
if((bitMask & current) == 0)
returnBit = 0;
else
returnBit = 1;
next--; // One fewer bit to return
bitMask = bitMask >> 1; // Shift to mask next bit
return returnBit;
}
else {
if((bitMask & current) == 0)
returnBit = 0;
else
returnBit = 1;
bitMask = bitMask >> 1; // Shift to mask next bit
if(bitMask == 0) { // Finished returning this byte?
bitMask = 128; // Leftmost bit next
current = next;
next = afterNext;
afterNext = input.read();
}
return returnBit;
}
}
/**
* Close this bitReader.
* @throws IOException
*/
public void close() throws IOException {
input.close();
}
}