Changed license to CC0
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / data / BitInputStream.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.commons.data;
6
7
8 import java.io.IOException;
9 import java.io.InputStream;
10
11 /**
12  * Read individual bits from the input stream.
13  */
14 public class BitInputStream {
15
16     private final InputStream inputStream;
17     private int currentByte;
18     private int currentBytePointer = -1;
19
20     public BitInputStream(final InputStream inputStream) {
21         this.inputStream = inputStream;
22     }
23
24     public int readBits(final int bitCount) throws IOException {
25
26         int readableByte = 0;
27         for (int i = 0; i < bitCount; i++) {
28
29             readableByte = readableByte << 1;
30
31             if (currentBytePointer == -1) {
32                 currentBytePointer = 7;
33                 currentByte = inputStream.read();
34             }
35
36             int mask = 1;
37             mask = mask << currentBytePointer;
38
39             final int currentBit = currentByte & mask;
40
41             if (currentBit != 0)
42                 readableByte = readableByte | 1;
43
44             currentBytePointer--;
45         }
46         return readableByte;
47     }
48
49 }