如果我有一个整数需要进行位操作,如何将它加载到 java.util.BitSet
中?如何将其转换回 int 或 long 类型?我不太关心 BitSet
的大小 - 它始终为32或64位长。我只想使用 set()
、clear()
、nextSetBit()
和 nextClearBit()
方法,而不是位运算符,但我找不到一个简单的方法来用数字类型初始化一个 bit set。
如果我有一个整数需要进行位操作,如何将它加载到 java.util.BitSet
中?如何将其转换回 int 或 long 类型?我不太关心 BitSet
的大小 - 它始终为32或64位长。我只想使用 set()
、clear()
、nextSetBit()
和 nextClearBit()
方法,而不是位运算符,但我找不到一个简单的方法来用数字类型初始化一个 bit set。
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;
}
}
编辑:现在是双向的,@leftbrain:当然,你是对的。
BitSet -> long
,你应该真正使用 BitSet.nextSetBit()
。 - charlie添加到finnw答案中:还有BitSet.valueOf(long[])
和BitSet.toLongArray()
。因此:
int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});
long l = bs.toLongArray()[0];
Java 7 提供了 BitSet.valueOf(byte[])
和 BitSet.toByteArray()
方法。
如果你使用的是 Java 6 或者更早的版本,可以考虑使用 BigInteger
. 如果性能不是主要瓶颈的话,BigInteger
有 getLowestSetBit
、setBit
和 clearBit
方法(后两个方法将创建一个新的 BigInteger
而非直接修改原始对象)。
BitSet
中获取一个long
,请参考以下内容:long l = bitSet.stream()
.takeWhile(i -> i < Long.SIZE)
.mapToLong(i -> 1L << i)
.reduce(0, (a, b) -> a | b);
反之亦然:
BitSet bitSet = IntStream.range(0, Long.SIZE - 1)
.filter(i -> 0 != (l & 1L << i))
.collect(BitSet::new, BitSet::set, BitSet::or);
BitSet::valueOf
和BitSet::toLongArray
更容易。value=0;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
value += (1 << i)
}
int[]
或long[]
。但是OP明确表示不关心,所以没问题。只有一些小错误:在使用long时,应该使用1L << i
来防止溢出,并且像value |= 1L << i
这样的OR操作就足够了。 - charliefun BitSet.toInt() =
toLongArray()
.getOrNull(0)
?.toInt()
?: 0
Int to BitSet扩展:
fun Int.toBitSet(size: Int): BitSet {
val byteArray = byteArrayOf(toByte())
return BitSet.valueOf(
if (byteArray.size == size) byteArray
else byteArray.copyOf(size))
}
val intValue = 1
val bitSetValue = intValue.toBitSet(size = 2)
println("bitSetValue: $bitSetValue")
val firstValue = bitSetValue.get(0)
println("firstValue: $firstValue")
val secondValue = bitSetValue.get(1)
println("secondValue: $secondValue")
bitSetValue.set(0, true)
bitSetValue.set(1, false)
println("bitSetValue: $bitSetValue")
val newIntValue = bitSetValue.toInt()
println("newIntValue: $newIntValue")
你不是在寻找 public void set(int bit)
方法吗?