int getBits(int n) {
        bitCount += n;
        int val = 0;
        int pos = bufferIndex;
        if (pos + n < BUFFER_SIZE) {
            while (n-- > 0) {
                val <<= 1;
                val |= ((buffer[pos++] != 0) ? 1 : 0);
            }
        } else {
            while (n-- > 0) {
                val <<= 1;
                val |= ((buffer[pos] != 0) ? 1 : 0);
                pos = (pos + 1) & BUFFER_SIZE_MASK;
            }
        }
        bufferIndex = pos;
        return val;
    }