java - 移动 Java 位集

标签 java bitset bit-shift

我正在使用 java.util.BitSet 来存储密集的位 vector 。

我想实现一个将位右移 1 的操作,类似于整数上的 >>>

有没有移动BitSets的库函数?

如果没有,有没有比下面更好的方法?

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/

相关文章:

c - 有效设置 N 个 X 位,从 MSB 的位置 P 开始

c - 为什么右移有两个选项? (算术/逻辑)

java - 连接到本地主机数据库

c++ - C++:如何获取位集的MSB(最高有效位)(使用按位运算符)?

java - Java Bitset 类与 Byte 数组的比较 - Byte 数组相对于 Bitset 类的优点

javascript - 按位运算正数转负数

assembly - 如何在不使用 MUL 或 DIV 的情况下在 5 行中将数字乘以 42?

java - 在 Solr 中的单个字段上启用小写搜索和 docValues

Java - 读入7个整数,计算重复出现的次数

java - 我将 TestNG 与 PowerMock 一起使用。它总是抛出未准备测试的类