public int readBits ( final JBBPBitNumber numOfBitsToRead ) throws IOException { int result ; final int numOfBitsAsNumber = numOfBitsToRead . getBitNumber ( ) ; if ( this . bitsInBuffer == 0 && numOfBitsAsNumber == 8 ) { result = this . readByteFromStream ( ) ; if ( result >= 0 ) { this . byteCounter ++ ; } return result ; } else { result = 0 ; if ( numOfBitsAsNumber == this . bitsInBuffer ) { result = this . bitBuffer ; this . bitBuffer = 0 ; this . bitsInBuffer = 0 ; this . byteCounter ++ ; return result ; } int i = numOfBitsAsNumber ; int theBitBuffer = this . bitBuffer ; int theBitBufferCounter = this . bitsInBuffer ; final boolean doIncCounter = theBitBufferCounter != 0 ; while ( i > 0 ) { if ( theBitBufferCounter == 0 ) { if ( doIncCounter ) { this . byteCounter ++ ; } final int nextByte = this . readByteFromStream ( ) ; if ( nextByte < 0 ) { if ( i == numOfBitsAsNumber ) { return nextByte ; } else { break ; } } else { theBitBuffer = nextByte ; theBitBufferCounter = 8 ; } } result = ( result << 1 ) | ( theBitBuffer & 1 ) ; theBitBuffer >>= 1 ; theBitBufferCounter -- ; i -- ; } this . bitBuffer = theBitBuffer ; this . bitsInBuffer = theBitBufferCounter ; return JBBPUtils . reverseBitsInByte ( JBBPBitNumber . decode ( numOfBitsAsNumber - i ) , ( byte ) result ) & 0xFF ; } }
Read number of bits from the input stream . It reads bits from input stream since 0 bit and make reversion to return bits in the right order when 0 bit is 0 bit . if the stream is completed early than the data read then reading is just stopped and read value returned . The First read bit is placed as 0th bit .