BitSet与整数/长整数

ata*_*lor 52 java bit-manipulation bitset

如果我有一个我想要执行位操作的整数,我该如何将其加载到java.util.BitSet?如何将其转换回int或long?我不太关心BitSet它的大小- 它总是32或64位长.我只是想使用set(),clear(),nextSetBit(),和nextClearBit()方法,而不是位运算符,但我无法找到一个简单的方法来初始化位以数字类型设置.

Arn*_*ter 54

以下代码从long值创建一个位集,反之亦然:

public class Bits {

  public static BitSet convert(long value) {
    BitSet bits = new BitSet();
    int index = 0;
    while (value != 0L) {
      if (value % 2L != 0) {
        bits.set(index);
      }
      ++index;
      value = value >>> 1;
    }
    return bits;
  }

  public static long convert(BitSet bits) {
    long value = 0L;
    for (int i = 0; i < bits.length(); ++i) {
      value += bits.get(i) ? (1L << i) : 0L;
    }
    return value;
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑:现在两个方向,@ leftbrain:原因,你是对的

  • 我认为行(值%1L!= 0)应该是(值%2L!= 0) (6认同)
  • 你真的应该使用 `BitSet.nextSetBit()` 来表示 `BitSet -&gt; long`。 (3认同)

GKi*_*lin 35

添加到finnw回答:还有BitSet.valueOf(long[])BitSet.toLongArray().所以:

int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});
long l = bs.toLongArray()[0];
Run Code Online (Sandbox Code Playgroud)


fin*_*nnw 18

Java 7有BitSet.valueOf(byte[])BitSet.toByteArray()

如果你被卡住的Java 6或更早的版本,你可以使用BigInteger,如果它是不太可能是一个性能瓶颈-它有getLowestSetBit,setBitclearBit(最后两个将创建一个新的方法BigInteger,而不是就地修改)


cha*_*lie 5

以“流畅”的方式long小事 中获得回报:BitSet

long l = bitSet.stream()
        .takeWhile(i -> i < Long.SIZE)
        .mapToLong(i -> 1L << i)
        .reduce(0, (a, b) -> a | b);
Run Code Online (Sandbox Code Playgroud)

反之亦然:

BitSet bitSet = IntStream.range(0, Long.SIZE - 1)
        .filter(i -> 0 != (l & 1L << i))
        .collect(BitSet::new, BitSet::set, BitSet::or);
Run Code Online (Sandbox Code Playgroud)

注意:使用BitSet::valueOfandBitSet::toLongArray当然更容易。