2 * Copyright 2007 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.common;
20 * <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
21 * number of bits read is not often a multiple of 8.</p>
23 * <p>This class is thread-safe but not reentrant -- unless the caller modifies the bytes array
24 * it passed in, in which case all bets are off.</p>
28 public final class BitSource {
30 private final byte[] bytes;
31 private int byteOffset;
32 private int bitOffset;
35 * @param bytes bytes from which this will read bits. Bits will be read from the first byte first.
36 * Bits are read within a byte from most-significant to least-significant bit.
38 public BitSource(byte[] bytes) {
43 * @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.
45 public int getBitOffset() {
50 * @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.
52 public int getByteOffset() {
57 * @param numBits number of bits to read
58 * @return int representing the bits read. The bits will appear as the least-significant
60 * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available
62 public int readBits(int numBits) {
63 if (numBits < 1 || numBits > 32 || numBits > available()) {
64 throw new IllegalArgumentException(String.valueOf(numBits));
69 // First, read remainder from current byte
71 int bitsLeft = 8 - bitOffset;
72 int toRead = numBits < bitsLeft ? numBits : bitsLeft;
73 int bitsToNotRead = bitsLeft - toRead;
74 int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
75 result = (bytes[byteOffset] & mask) >> bitsToNotRead;
84 // Next read whole bytes
86 while (numBits >= 8) {
87 result = (result << 8) | (bytes[byteOffset] & 0xFF);
92 // Finally read a partial byte
94 int bitsToNotRead = 8 - numBits;
95 int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
96 result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
105 * @return number of bits that can be read successfully
107 public int available() {
108 return 8 * (bytes.length - byteOffset) - bitOffset;