public int readBits ( int n ) throws IOException { assert ( n > 0 ) ; int result ; if ( n <= capacity ) { // buffer already holds all necessary bits result = ( buffer >> ( capacity -= n ) ) & ( 0xff >> ( BUFFER_CAPACITY - n ) ) ; } else if ( capacity == 0 && n == BUFFER_CAPACITY ) { // possible to read direct byte, nothing else to do result = readDirectByte ( ) ; } else { // get as many bits from buffer as possible result = buffer & ( 0xff >> ( BUFFER_CAPACITY - capacity ) ) ; n -= capacity ; capacity = 0 ; // possibly read whole bytes while ( n > 7 ) { if ( capacity == 0 ) { readBuffer ( ) ; } result = ( result << BUFFER_CAPACITY ) | buffer ; n -= BUFFER_CAPACITY ; capacity = 0 ; } // read the rest of the bits if ( n > 0 ) { if ( capacity == 0 ) { readBuffer ( ) ; } result = ( result << n ) | ( buffer >> ( capacity = ( BUFFER_CAPACITY - n ) ) ) ; } } return result ; }
Read the next n bits and return the result as an integer .