Code cleanup and formatting. Migrated to java 1.8.
[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     private final OutputStream outputStream;
22     private int currentByte;
23     private int currentBytePointer;
24
25     public BitOutputStream(final OutputStream outputStream) {
26         currentByte = 0;
27         currentBytePointer = 0;
28         this.outputStream = outputStream;
29     }
30
31     public void finishByte() throws IOException {
32         if (currentBytePointer != 0) {
33             outputStream.write(currentByte);
34             currentBytePointer = 0;
35         }
36     }
37
38     public void storeBits(final int data, final int bitCount)
39             throws IOException {
40         for (int i = bitCount - 1; i >= 0; i--) {
41
42             int mask = 1;
43             mask = mask << i;
44
45             final int currentBit = data & mask;
46             currentByte = currentByte << 1;
47
48             if (currentBit != 0)
49                 currentByte = currentByte | 1;
50             currentBytePointer++;
51
52             if (currentBytePointer == 8) {
53                 currentBytePointer = 0;
54                 outputStream.write(currentByte);
55                 currentByte = 0;
56             }
57         }
58     }
59
60 }