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 >
Please find this code block where BitSet is "left-shifted"
/**
* Shift the BitSet to left.
* For example : 0b10010 (=18) => 0b100100 (=36) (equivalent to multiplicate by 2)
* @param bitSet
* @return shifted bitSet
*/
public static BitSet leftShiftBitSet(BitSet bitSet) {
final long maskOfCarry = 0x8000000000000000L;
long[] aLong = bitSet.toLongArray();
boolean carry = false;
for (int i = 0; i < aLong.length; ++i) {
if (carry) {
carry = ((aLong[i] & maskOfCarry) != 0);
aLong[i] <<= 1;
++aLong[i];
} else {
carry = ((aLong[i] & maskOfCarry) != 0);
aLong[i] <<= 1;
}
}
if (carry) {
long[] tmp = new long[aLong.length + 1];
System.arraycopy(aLong, 0, tmp, 0, aLong.length);
++tmp[aLong.length];
aLong = tmp;
}
return BitSet.valueOf(aLong);
}