public void flushBits() throws IOException {
        //
        // If the buffer has fewer than 8 bits, need to shift the bits
        // left to align them with the left end of the byte before 
        // writing out.  
        // NOTE: when you read in the bits, there may be some 
        // extra 0 bits dangling at the end!
        //
        if (numBits < 8) {
            buffer = (byte)(buffer << (8 - numBits));
        }
    
        out.write(buffer);
        numBytesWritten++;

        // Clear the buffer.
        buffer = 0;
        numBits = 0;
    }