initial commit
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / data / BitInputStream.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright (C) 2012, 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 2 of the GNU General Public License
7  * 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
51                         currentBytePointer--;
52                 }
53                 return readableByte;
54         }
55
56         public int readIntegerCompressed8() throws IOException {
57                 if (readBits(1) == 0) {
58                         return readBits(8);
59                 } else {
60                         return readBits(32);
61                 }
62         }
63
64 }