5 * Created by Christian Brunschen on 09/05/2008.
6 * Copyright 2008 Google UK. All rights reserved.
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
21 #include <zxing/common/BitSource.h>
22 #include <zxing/common/IllegalArgumentException.h>
26 int BitSource::readBits(int numBits) {
27 if (numBits < 0 || numBits > 32) {
28 throw IllegalArgumentException("cannot read <1 or >32 bits");
29 } else if (numBits > available()) {
30 throw IllegalArgumentException("reading more bits than are available");
36 // First, read remainder from current byte
38 int bitsLeft = 8 - bitOffset_;
39 int toRead = numBits < bitsLeft ? numBits : bitsLeft;
40 int bitsToNotRead = bitsLeft - toRead;
41 int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
42 result = (bytes_[byteOffset_] & mask) >> bitsToNotRead;
45 if (bitOffset_ == 8) {
51 // Next read whole bytes
53 while (numBits >= 8) {
54 result = (result << 8) | (bytes_[byteOffset_] & 0xFF);
60 // Finally read a partial byte
62 int bitsToNotRead = 8 - numBits;
63 int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
64 result = (result << numBits) | ((bytes_[byteOffset_] & mask) >> bitsToNotRead);
65 bitOffset_ += numBits;
72 int BitSource::available() {
73 return 8 * (bytes_.size() - byteOffset_) - bitOffset_;