GreyscaleRotatedLuminanceSource: implemented getMatrix()
[zxing.git] / cpp / core / src / zxing / common / BitSource.cpp
1 /*
2  *  BitSource.cpp
3  *  zxing
4  *
5  *  Created by Christian Brunschen on 09/05/2008.
6  *  Copyright 2008 Google UK. All rights reserved.
7  *
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  */
20
21 #include <zxing/common/BitSource.h>
22 #include <zxing/common/IllegalArgumentException.h>
23
24 namespace zxing {
25
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");
31   }
32
33   int result = 0;
34
35
36   // First, read remainder from current byte
37   if (bitOffset_ > 0) {
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;
43     numBits -= toRead;
44     bitOffset_ += toRead;
45     if (bitOffset_ == 8) {
46       bitOffset_ = 0;
47       byteOffset_++;
48     }
49   }
50
51   // Next read whole bytes
52   if (numBits > 0) {
53     while (numBits >= 8) {
54       result = (result << 8) | (bytes_[byteOffset_] & 0xFF);
55       byteOffset_++;
56       numBits -= 8;
57     }
58
59
60     // Finally read a partial byte
61     if (numBits > 0) {
62       int bitsToNotRead = 8 - numBits;
63       int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
64       result = (result << numBits) | ((bytes_[byteOffset_] & mask) >> bitsToNotRead);
65       bitOffset_ += numBits;
66     }
67   }
68
69   return result;
70 }
71
72 int BitSource::available() {
73   return 8 * (bytes_.size() - byteOffset_) - bitOffset_;
74 }
75 }