//package com.nowjava;
/**
* 时 代 J a v a - N o w J a v a . c o m 提 供
**/
public class Main {
public static void main(String[] argv) throws Exception {
int bitset = 2;
int fromIndex = 2;
System.out.println(nextSetBit(bitset, fromIndex));
}
/** maximum index of a bitset (minimum index is 0) */
public static final int MAX_INDEX = 31;
/*
*来 自
时代Java公众号 - nowjava.com
*/
/** 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 >= 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}.
*
/**代码未完, 请加载全部代码(NowJava.com).**/
本文系作者在时代Java发表,未经许可,不得转载。如有侵权,请联系nowjava@qq.com删除。