Shifting a Java BitSet

后端 未结 8 1536
太阳男子
太阳男子 2020-12-31 00:11

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

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

相关标签:
8条回答
  • 2020-12-31 00:58

    That should do the trick:

    BitSet shifted = bs.get(1, bs.length());
    

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

    EDIT:

    To generalize this to n bits,

    BitSet shifted = bs.get(n, Math.max(n, bs.length()));
    
    0 讨论(0)
  • 2020-12-31 00:59

    With java SE8, it can be achieved more concise way:

    BitSet b = new BitSet();
    b.set(1, 3);
    BitSet shifted = BitSet.valueOf(Arrays.stream(
           b.toLongArray()).map(v -> v << 1).toArray());
    

    I was trying to figure out how to use LongBuffer to do so but not quite got it to work. Hopefully, someone who is familiar with low level programming can point out a solution.

    Thanks in advance!!!

    0 讨论(0)
提交回复
热议问题