Code cleanup and formatting. Migrated to java 1.8.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / data / BitInputStream.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2014, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.commons.data;
11
12 /**
13  * Read individual bits from the input stream.
14  */
15
16 import java.io.IOException;
17 import java.io.InputStream;
18
19 public class BitInputStream {
20
21     private final InputStream inputStream;
22     private int currentByte;
23     private int currentBytePointer = -1;
24
25     public BitInputStream(final InputStream inputStream) {
26         this.inputStream = inputStream;
27     }
28
29     public int readBits(final int bitCount) throws IOException {
30
31         int readableByte = 0;
32         for (int i = 0; i < bitCount; i++) {
33
34             readableByte = readableByte << 1;
35
36             if (currentBytePointer == -1) {
37                 currentBytePointer = 7;
38                 currentByte = inputStream.read();
39             }
40
41             int mask = 1;
42             mask = mask << currentBytePointer;
43
44             final int currentBit = currentByte & mask;
45
46             if (currentBit != 0)
47                 readableByte = readableByte | 1;
48
49             currentBytePointer--;
50         }
51         return readableByte;
52     }
53
54 }