转移Java BitSet [英] Shifting a Java BitSet

查看:274
本文介绍了转移Java BitSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 java.util.BitSet 来存储密集的位向量。

I am using a java.util.BitSet to store a dense vector of bits.

我想要实现一个将位向右移1的操作,类似于>>> on int。

I want to implement an operation that shifts the bits right by 1, analogous to >>> on ints.

是否存在移位 BitSet s的库函数?

Is there a library function that shifts BitSets?

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

If not, is there a better way than the below?

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());

它会给你一个等于orginial的位集,但没有最低位。

It will give you a bitset equal to the orginial one, but without the lower-most bit.

编辑:

将此概括为 n 位,

BitSet shifted = bs.get(n, Math.max(n, bs.length()));

这篇关于转移Java BitSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆