Search code examples
javabit-shiftbitset

Is it possible to shift a Java BitSet using the logical operators?


For example I have a BitSet BitSet x = new BitSet(32); and I set bit 3 x.set(2, true);
Is there anyways to do a logical shift like x << someAmount; that pads with 0's?


Solution

  • Here is how you would shift them right and left 8 bits.

    BitSet bits = new BitSet();
    bits.set(10);
    bits.set(30);
    System.out.println("unshifted:" + bits);
    System.out.println("right shift: " + shift(bits, 8));
    System.out.println("left shift: " + shift(bits,-8));
    

    Prints

    unshifted: {10, 30}
    right shift: {18, 38}
    left shift: {2, 22}
    

    Here is the method

    • it streams the current positions
    • and adjusts them based on the shift amount.
    • Positions due to negative shifts are dropped as they would be out of range.
    • the new BitSet is returned.
        
    public static BitSet shift(BitSet bitset, int shiftAmount) {
        BitSet b = new BitSet();
        bitset.stream().map(bitPos -> bitPos + shiftAmount)
                .dropWhile(bitPos -> bitPos < 0)
                .forEach(bitPos -> b.set(bitPos));
        return b;
    }
    

    Note the a BitSet is oriented starting with 1,2,4,8 which is opposite of a normal binary number. Also note that in the above left shifted bits will lose trailing zeros. Right shifted will gain padded ones on the left.