Changed license to LGPLv3 or later.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / data / BitOutputStream.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  * Write individual bits to the output stream.
14  */
15
16 import java.io.IOException;
17 import java.io.OutputStream;
18
19 public class BitOutputStream {
20
21         int currentByte;
22         int currentBytePointer;
23
24         OutputStream outputStream;
25
26         public BitOutputStream(final OutputStream outputStream) {
27                 currentByte = 0;
28                 currentBytePointer = 0;
29                 this.outputStream = outputStream;
30         };
31
32         public void finishByte() throws IOException {
33                 if (currentBytePointer != 0) {
34                         outputStream.write(currentByte);
35                         currentBytePointer = 0;
36                 }
37         }
38
39         public void storeBits(final int data, final int bitCount)
40                         throws IOException {
41                 for (int i = bitCount - 1; i >= 0; i--) {
42
43                         int mask = 1;
44                         mask = mask << i;
45
46                         final int currentBit = data & mask;
47                         currentByte = currentByte << 1;
48
49                         if (currentBit != 0)
50                                 currentByte = currentByte | 1;
51                         currentBytePointer++;
52
53                         if (currentBytePointer == 8) {
54                                 currentBytePointer = 0;
55                                 outputStream.write(currentByte);
56                                 currentByte = 0;
57                         }
58                 }
59         }
60
61         public void storeIntegerCompressed8(final int data) throws IOException {
62                 if (data < 256) {
63                         storeBits(0, 1);
64                         storeBits(data, 8);
65                 } else {
66                         storeBits(1, 1);
67                         storeBits(data, 32);
68                 }
69         }
70
71 }