readBits method

int readBits(
  1. int bitsLength
)

Reads and returns the specified number of bits from the internal buffer.

Parameters:

  • bitsLength: The number of bits to be read from the internal buffer.

Returns an integer containing the read bits.

Implementation

int readBits(int bitsLength) {
  if (bitsLength == 8 && _bitsBufferLength == 0) {
    return _bytesBuffer.readByte();
  }

  while (_bitsBufferLength < bitsLength) {
    var rb = _bytesBuffer.readByte();
    _bitsBuffer = (_bitsBuffer << 8) | (rb & 0xFF);
    _bitsBufferLength += 8;
  }

  if (bitsLength == _bitsBufferLength) {
    var b = _bitsBuffer;
    _bitsBuffer = 0;
    _bitsBufferLength = 0;
    return b;
  }

  var extraBits = _bitsBufferLength - bitsLength;

  var bMask = (1 << bitsLength) - 1;
  assert(bMask > 0);
  var bMask2 = (1 << extraBits) - 1;

  var b = (_bitsBuffer >>> extraBits) & bMask;

  _bitsBuffer = _bitsBuffer & bMask2;
  _bitsBufferLength -= bitsLength;

  return b;
}