initial commit
[imagesqueeze.git] / src / main / java / eu / svjatoslav / imagesqueeze / codec / BitInputStream.java
1 package eu.svjatoslav.imagesqueeze.codec;
2
3 /**
4  * Read individual bits from the input stream.
5  */
6
7 import java.io.IOException;
8 import java.io.InputStream;
9
10 public class BitInputStream {
11
12
13         int currentByte;
14         int currentBytePointer = -1;
15
16         InputStream inputStream;
17
18         public BitInputStream(InputStream inputStream){
19                 this.inputStream = inputStream;
20         }
21
22         public int readBits(int bitCount) throws IOException {
23
24                 int readableByte = 0;
25                 for (int i=0; i < bitCount; i++){
26
27                         readableByte = readableByte << 1;
28
29                         if (currentBytePointer == -1){
30                                 currentBytePointer = 7;
31                                 currentByte = inputStream.read();
32                         }
33
34                         int mask = 1;
35                         mask = mask << currentBytePointer;
36
37                         int currentBit = currentByte & mask;
38
39                         if (currentBit != 0){
40                                 readableByte = readableByte | 1;
41                         }
42
43                         currentBytePointer--;
44                 }
45                 return readableByte;
46         }
47
48         public int readIntegerCompressed8() throws IOException{
49                 if (readBits(1) == 0){
50                         return readBits(8);
51                 } else {
52                         return readBits(32);                    
53                 }               
54         }
55
56 }