|
| 1 | +import java.io.*; |
| 2 | + |
| 3 | +/* |
| 4 | + * A BitInputStream lets you read in the contents of a binary file in |
| 5 | + * units of: one bit (a single binary digit), one byte (8 bits), and |
| 6 | + * one 4-byte word (32 bits). The bits that form a byte or a word do |
| 7 | + * not have to be byte aligned. |
| 8 | + */ |
| 9 | +public class BitInputStream implements AutoCloseable { |
| 10 | + private byte[] bytes; |
| 11 | + private int index; |
| 12 | + |
| 13 | + public BitInputStream(File in) throws FileNotFoundException, IOException { |
| 14 | + this(new FileInputStream(in)); |
| 15 | + } |
| 16 | + |
| 17 | + public BitInputStream(FileInputStream fileInputStream) throws IOException { |
| 18 | + DataInputStream in = new DataInputStream(fileInputStream); |
| 19 | + int size = in.available(); |
| 20 | + this.bytes = new byte[size]; |
| 21 | + this.index = 0; |
| 22 | + in.read(bytes); |
| 23 | + in.close(); |
| 24 | + } |
| 25 | + |
| 26 | + /* |
| 27 | + * Returns the file size as a count of bytes. |
| 28 | + */ |
| 29 | + public int size() { |
| 30 | + return bytes.length; |
| 31 | + } |
| 32 | + |
| 33 | + public byte[] allBytes() { |
| 34 | + return bytes; |
| 35 | + } |
| 36 | + |
| 37 | + public int readBit() throws IOException { |
| 38 | + byte b = bytes[index / 8]; |
| 39 | + int offset = index % 8; |
| 40 | + final int mask = 1 << 7; |
| 41 | + ++index; |
| 42 | + return (b & (mask >>> offset)) == 0 ? 0 : 1; |
| 43 | + } |
| 44 | + |
| 45 | + public int readByte() throws IOException { |
| 46 | + byte value = 0; |
| 47 | + for (int i = 0; i < 8; ++i) { |
| 48 | + value <<= 1; |
| 49 | + value |= readBit(); |
| 50 | + } |
| 51 | + return value & 0xFF; |
| 52 | + } |
| 53 | + |
| 54 | + public int readInt() throws IOException { |
| 55 | + int value = readByte(); |
| 56 | + value = (value << 8) | readByte(); |
| 57 | + value = (value << 8) | readByte(); |
| 58 | + value = (value << 8) | readByte(); |
| 59 | + return value; |
| 60 | + } |
| 61 | + |
| 62 | + public void close() throws IOException { |
| 63 | + // intentionally left blank |
| 64 | + } |
| 65 | +} |
0 commit comments