2 * Copyright 2007 Google Inc.
\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.qrcode.decoder;
\r
20 * This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
\r
21 * number of bits read is not often a multiple of 8.
\r
23 * @author srowen@google.com (Sean Owen)
\r
25 final class BitSource {
\r
27 private final byte[] bytes;
\r
28 private int byteOffset;
\r
29 private int bitOffset;
\r
31 BitSource(byte[] bytes) {
\r
36 * @throws IllegalArgumentException if numBits isn't in [1,32]
\r
38 int readBits(int numBits) {
\r
39 if (numBits < 1 || numBits > 32) {
\r
40 throw new IllegalArgumentException();
\r
45 // First, read remainder from current byte
\r
46 if (bitOffset > 0) {
\r
47 int bitsLeft = 8 - bitOffset;
\r
48 int toRead = numBits < bitsLeft ? numBits : bitsLeft;
\r
49 int bitsToNotRead = bitsLeft - toRead;
\r
50 int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
\r
51 result = (bytes[byteOffset] & mask) >> bitsToNotRead;
\r
53 bitOffset += toRead;
\r
54 if (bitOffset == 8) {
\r
60 // Next read whole bytes
\r
62 while (numBits >= 8) {
\r
63 result = (result << 8) | (bytes[byteOffset] & 0xFF);
\r
68 // Finally read a partial byte
\r
70 int bitsToNotRead = 8 - numBits;
\r
71 int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
\r
72 result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);
\r
73 bitOffset += numBits;
\r
81 return 8 * (bytes.length - byteOffset) - bitOffset;
\r