initial commit
[imagesqueeze.git] / src / main / java / eu / svjatoslav / imagesqueeze / codec / BitOutputStream.java
1 package eu.svjatoslav.imagesqueeze.codec;
2
3 /**
4  * Write individual bits to the output stream.
5  */
6
7 import java.io.IOException;
8 import java.io.OutputStream;
9
10 public class BitOutputStream {
11
12         int currentByte;
13         int currentBytePointer;
14         
15         OutputStream outputStream;
16
17         public BitOutputStream(OutputStream outputStream){
18                 currentByte = 0;
19                 currentBytePointer = 0;
20                 this.outputStream = outputStream;
21         };
22
23
24         public void storeBits(int data, int bitCount) throws IOException {
25                 for (int i=bitCount-1; i >= 0; i--){
26
27                         int mask = 1;
28                         mask = mask << i;
29
30                         int currentBit = data & mask;
31                         currentByte = currentByte << 1;
32
33                         if (currentBit != 0){
34                                 currentByte = currentByte | 1;
35                         }
36                         currentBytePointer++;
37
38                         if (currentBytePointer == 8){
39                                 currentBytePointer = 0;
40                                 outputStream.write(currentByte);
41                                 currentByte = 0;
42                         }
43                 }
44         }
45
46         public void storeIntegerCompressed8(int data) throws IOException{
47                 if (data < 256){
48                         storeBits(0, 1);
49                         storeBits(data, 8);
50                 } else {
51                         storeBits(1, 1);
52                         storeBits(data, 32);                    
53                 }               
54         }
55
56         public void finishByte() throws IOException {
57                 if (currentBytePointer != 0){
58                         outputStream.write(currentByte);                                        
59                         currentBytePointer = 0;
60                 }
61         }       
62
63 }