| 20 | } |
| 21 | |
| 22 | static int ReadBitsImpl(int numBits, const ByteArray& _bytes, int available, int& _byteOffset, int& _bitOffset) |
| 23 | { |
| 24 | if (numBits < 1 || numBits > 32 || numBits > available) { |
| 25 | throw std::out_of_range("BitSource::readBits: out of range"); |
| 26 | } |
| 27 | |
| 28 | int result = 0; |
| 29 | |
| 30 | // First, read remainder from current byte |
| 31 | if (_bitOffset > 0) { |
| 32 | int bitsLeft = 8 - _bitOffset; |
| 33 | int toRead = numBits < bitsLeft ? numBits : bitsLeft; |
| 34 | int bitsToNotRead = bitsLeft - toRead; |
| 35 | int mask = (0xFF >> (8 - toRead)) << bitsToNotRead; |
| 36 | result = (_bytes[_byteOffset] & mask) >> bitsToNotRead; |
| 37 | numBits -= toRead; |
| 38 | _bitOffset += toRead; |
| 39 | if (_bitOffset == 8) { |
| 40 | _bitOffset = 0; |
| 41 | _byteOffset++; |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | // Next read whole bytes |
| 46 | if (numBits > 0) { |
| 47 | while (numBits >= 8) { |
| 48 | result = (result << 8) | _bytes[_byteOffset]; |
| 49 | _byteOffset++; |
| 50 | numBits -= 8; |
| 51 | } |
| 52 | |
| 53 | // Finally read a partial byte |
| 54 | if (numBits > 0) { |
| 55 | int bitsToNotRead = 8 - numBits; |
| 56 | int mask = (0xFF >> bitsToNotRead) << bitsToNotRead; |
| 57 | result = (result << numBits) | ((_bytes[_byteOffset] & mask) >> bitsToNotRead); |
| 58 | _bitOffset += numBits; |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | return result; |
| 63 | } |
| 64 | |
| 65 | int BitSource::readBits(int numBits) |
| 66 | { |