2 * Copyright 2008 ZXing authors
\r
4 * Licensed under the Apache License, Version 2.0 (the "License");
\r
5 * you may not use this file except in compliance with the License.
\r
6 * You may obtain a copy of the License at
\r
8 * http://www.apache.org/licenses/LICENSE-2.0
\r
10 * Unless required by applicable law or agreed to in writing, software
\r
11 * distributed under the License is distributed on an "AS IS" BASIS,
\r
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
13 * See the License for the specific language governing permissions and
\r
14 * limitations under the License.
\r
17 package com.google.zxing.common;
\r
19 import java.io.ByteArrayOutputStream;
\r
22 * Class that lets one easily build an array of bytes by appending bits at a time.
\r
24 * @author srowen@google.com (Sean Owen)
\r
26 public final class BitSourceBuilder {
\r
28 private final ByteArrayOutputStream output;
\r
29 private int nextByte;
\r
30 private int bitsLeftInNextByte;
\r
32 public BitSourceBuilder() {
\r
33 output = new ByteArrayOutputStream();
\r
35 bitsLeftInNextByte = 8;
\r
38 public void write(int value, int numBits) {
\r
39 if (numBits <= bitsLeftInNextByte) {
\r
40 nextByte <<= numBits;
\r
42 bitsLeftInNextByte -= numBits;
\r
43 if (bitsLeftInNextByte == 0) {
\r
44 output.write(nextByte);
\r
46 bitsLeftInNextByte = 8;
\r
49 int bitsToWriteNow = bitsLeftInNextByte;
\r
50 int numRestOfBits = numBits - bitsToWriteNow;
\r
51 int mask = 0xFF >> (8 - bitsToWriteNow);
\r
52 int valueToWriteNow = (value >>> numRestOfBits) & mask;
\r
53 write(valueToWriteNow, bitsToWriteNow);
\r
54 write(value, numRestOfBits);
\r
58 public byte[] toByteArray() {
\r
59 if (bitsLeftInNextByte < 8) {
\r
60 write(0, bitsLeftInNextByte);
\r
62 return output.toByteArray();
\r