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?
Asked
Active
Viewed 212 times
2

Frank Fiumara
- 120
- 1
- 15
-
2There was [a question primarily about right-shifting a BitSet](https://stackoverflow.com/q/9008150/555045), it has some answers that address left-shifting as well, with various different quirks.. is that good enough? – harold Sep 22 '21 at 19:55
-
That definitely works, I was just curious if the actual in-built operator could be used directly or indirectly to alter the BitSet – Frank Fiumara Sep 22 '21 at 20:02
-
5Java does not support operator overloading, so no, you can't use `<<` in Java. I'm surprised that `BitSet` doesn't have a `shift` method; I suppose you could subclass it and intercept all of the operations to offset the parameters. – chrylis -cautiouslyoptimistic- Sep 22 '21 at 20:05
-
That's the answer I was looking for. I also find it odd that there is no built in form of shifting. – Frank Fiumara Sep 22 '21 at 20:15
1 Answers
1
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.

WJS
- 36,363
- 4
- 24
- 39
-
Interesting. So I'll take it that the ```<<``` and ```>>``` operators can't be used this way then. – Frank Fiumara Sep 22 '21 at 20:14
-
1No. However, one could manipulate the long array which holds all the bits in the bitSet. That might also be more optimal but must take into account when large values are shifted as the longs would need to be shifted and or'd to accommodate the shift. The above method, imo, is more straight forward and certainly easier to implement. – WJS Sep 22 '21 at 20:51
-
That was my current approach. Your implementation is definitely simpler than what I have currently. – Frank Fiumara Sep 22 '21 at 21:16
-
I was thinking about this and depending on what you have to do, you could use a `BigInteger` which allows arbitrarily large values. It has various methods to allow bit manipulation. For what `BigInteger` does it is pretty efficient. – WJS Sep 23 '21 at 00:16