我正在使用 java.util.BitSet
来存储密集的位 vector 。
我想实现一个将位右移 1 的操作,类似于整数上的 >>>
。
有没有移动BitSet
s的库函数?
如果没有,有没有比下面更好的方法?
public static void logicalRightShift(BitSet bs) {
for (int i = 0; (i = bs.nextSetBit(i)) >= 0;) {
// i is the first bit in a run of set bits.
// Set any bit to the left of the run.
if (i != 0) { bs.set(i - 1); }
// Now i is the index of the bit after the end of the run.
i = bs.nextClearBit(i); // nextClearBit never returns -1.
// Clear the last bit of the run.
bs.clear(i - 1);
// 0000111100000...
// a b
// i starts off the loop at a, and ends the loop at b.
// The mutations change the run to
// 0001111000000...
}
}
最佳答案
这应该可以解决问题:
BitSet shifted = bs.get(1, bs.length());
它会给你一个等于原始的位集,但没有最低位。
编辑:
将其推广到 n
位,
BitSet shifted = bs.get(n, Math.max(n, bs.length()));
关于java - 移动 Java 位集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9008150/