Changed license to LGPLv3 or later.
[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         int currentByte;
22         int currentBytePointer = -1;
23
24         InputStream inputStream;
25
26         public BitInputStream(final InputStream inputStream) {
27                 this.inputStream = inputStream;
28         }
29
30         public int readBits(final int bitCount) throws IOException {
31
32                 int readableByte = 0;
33                 for (int i = 0; i < bitCount; i++) {
34
35                         readableByte = readableByte << 1;
36
37                         if (currentBytePointer == -1) {
38                                 currentBytePointer = 7;
39                                 currentByte = inputStream.read();
40                         }
41
42                         int mask = 1;
43                         mask = mask << currentBytePointer;
44
45                         final int currentBit = currentByte & mask;
46
47                         if (currentBit != 0)
48                                 readableByte = readableByte | 1;
49
50                         currentBytePointer--;
51                 }
52                 return readableByte;
53         }
54
55         public int readIntegerCompressed8() throws IOException {
56                 if (readBits(1) == 0)
57                         return readBits(8);
58                 else
59                         return readBits(32);
60         }
61
62 }