Returns the index of the first bit that is set to true that occurs on or after the specified starting index. - Java Language Basics

Java examples for Language Basics:Bit

Description

Returns the index of the first bit that is set to true that occurs on or after the specified starting index.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int bitset = 2;
        int fromIndex = 2;
        System.out.println(nextSetBit(bitset, fromIndex));
    }/*from w w w  .j ava2  s . c  o m*/

    /** maximum index of a bitset (minimum index is 0) */
    public static final int MAX_INDEX = 31;
    /** int with all bits set */
    public static final int INT_MASK = 0xffffffff;

    /**
     * Returns the index of the first bit that is set to <code>true</code> that
     * occurs on or after the specified starting index. If no such bit exists
     * then -1 is returned.
     * 
     * To iterate over the <code>true</code> bits in a bitset, use the following
     * loop:
     * 
     * <pre>
     * for (int i = nextSetBit(bitset, 0); i &gt;= 0; i = nextSetBit(bitset, i + 1))
     *     ; // do something
     * </pre>
     * 
     * @param  bitset
     *         a bitset.
     * @param  fromIndex
     *         the bit index after which the first bit that is set to
     *         <code>true</code> is returned.
     * @return the index of the first bit that is set to <code>true</code> that
     *         occurs on or after the specified starting index
     * @throws IndexOutOfBoundsException
     *         if the specified index is negative
     */
    public static int nextSetBit(int bitset, int fromIndex)
            throws IndexOutOfBoundsException {
        checkIndexRange(fromIndex, Integer.MAX_VALUE);
        if (fromIndex > MAX_INDEX)
            return -1;
        bitset &= (INT_MASK << fromIndex);
        if (bitset != 0)
            return Integer.numberOfTrailingZeros(bitset);
        return -1;
    }

    /**
     * Throws an {@link IndexOutOfBoundsException} if the given bit index is
     * negative or if it the second argument is <code>true</code> also if the
     * index is greater than {@link #MAX_INDEX}.
     * 
     * @param  index
     * @param  checkMax
     * @throws IndexOutOfBoundsException
     */
    private static void checkIndexRange(int index, int maxIndex)
            throws IndexOutOfBoundsException {
        if (index < 0 || index > maxIndex)
            throw new IndexOutOfBoundsException("bitIndex [0..."
                    + MAX_INDEX + "]: " + index);
    }
}

Related Tutorials