-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitInputStream.java
More file actions
65 lines (56 loc) · 1.55 KB
/
BitInputStream.java
File metadata and controls
65 lines (56 loc) · 1.55 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
import java.io.*;
/*
* A BitInputStream lets you read in the contents of a binary file in
* units of: one bit (a single binary digit), one byte (8 bits), and
* one 4-byte word (32 bits). The bits that form a byte or a word do
* not have to be byte aligned.
*/
public class BitInputStream implements AutoCloseable {
private byte[] bytes;
private int index;
public BitInputStream(File in) throws FileNotFoundException, IOException {
this(new FileInputStream(in));
}
public BitInputStream(FileInputStream fileInputStream) throws IOException {
DataInputStream in = new DataInputStream(fileInputStream);
int size = in.available();
this.bytes = new byte[size];
this.index = 0;
in.read(bytes);
in.close();
}
/*
* Returns the file size as a count of bytes.
*/
public int size() {
return bytes.length;
}
public byte[] allBytes() {
return bytes;
}
public int readBit() throws IOException {
byte b = bytes[index / 8];
int offset = index % 8;
final int mask = 1 << 7;
++index;
return (b & (mask >>> offset)) == 0 ? 0 : 1;
}
public int readByte() throws IOException {
byte value = 0;
for (int i = 0; i < 8; ++i) {
value <<= 1;
value |= readBit();
}
return value & 0xFF;
}
public int readInt() throws IOException {
int value = readByte();
value = (value << 8) | readByte();
value = (value << 8) | readByte();
value = (value << 8) | readByte();
return value;
}
public void close() throws IOException {
// intentionally left blank
}
}