-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitInputStream.java
More file actions
69 lines (51 loc) · 1.8 KB
/
Copy pathBitInputStream.java
File metadata and controls
69 lines (51 loc) · 1.8 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
package nayuki.arithcode;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
/**
* A stream of bits that can be read. Because they come from an underlying byte stream, the total number of bits is always a multiple of 8. The bits are read in big endian.
*/
public final class BitInputStream {
// Underlying byte stream to read from.
private InputStream input;
// Either in the range 0x00 to 0xFF if bits are available, or is -1 if the end of stream is reached.
private int nextBits;
// Always between 0 and 7, inclusive.
private int numBitsRemaining;
private boolean isEndOfStream;
// Creates a bit input stream based on the given byte input stream.
public BitInputStream(InputStream in) {
if (in == null)
throw new NullPointerException("Argument is null");
input = in;
numBitsRemaining = 0;
isEndOfStream = false;
}
// Reads a bit from the stream. Returns 0 or 1 if a bit is available, or -1 if the end of stream is reached. The end of stream always occurs on a byte boundary.
public int read() throws IOException {
if (isEndOfStream)
return -1;
if (numBitsRemaining == 0) {
nextBits = input.read(); // read one byte, but return an int.
if (nextBits == -1) {
isEndOfStream = true;
return -1;
}
numBitsRemaining = 8;
}
numBitsRemaining--;
return (nextBits >>> numBitsRemaining) & 1; // get LSB
}
// Reads a bit from the stream. Returns 0 or 1 if a bit is available, or throws an EOFException if the end of stream is reached.
public int readNoEof() throws IOException {
int result = read();
if (result != -1)
return result;
else
throw new EOFException("End of stream reached");
}
// Closes this stream and the underlying InputStream.
public void close() throws IOException {
input.close();
}
}