readBits method

int readBits(
  1. int numBits
)

@param numBits number of bits to read @return int representing the bits read. The bits will appear as the least-significant bits of the int @throws IllegalArgumentException if numBits isn't in 1,32 or more than is available

Implementation

int readBits(int numBits) {
  if (numBits < 1 || numBits > 32 || numBits > available()) {
    throw ArgumentError(numBits.toString());
  }

  int result = 0;

  // First, read remainder from current byte
  if (_bitOffset > 0) {
    final bitsLeft = 8 - _bitOffset;
    final toRead = math.min(numBits, bitsLeft);
    final bitsToNotRead = bitsLeft - toRead;
    final mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
    result = (_bytes[_byteOffset] & mask) >> bitsToNotRead;
    numBits -= toRead;
    _bitOffset += toRead;
    if (_bitOffset == 8) {
      _bitOffset = 0;
      _byteOffset++;
    }
  }

  // Next read whole bytes
  if (numBits > 0) {
    while (numBits >= 8) {
      result = (result << 8) | _bytes[_byteOffset];
      _byteOffset++;
      numBits -= 8;
    }

    // Finally read a partial byte
    if (numBits > 0) {
      final int bitsToNotRead = 8 - numBits;
      final int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
      result = (result << numBits) |
          ((_bytes[_byteOffset] & mask) >> bitsToNotRead);
      _bitOffset += numBits;
    }
  }

  return result;
}