If I have an integer that I'd like to perform bit manipulation on, how can I load it into a java.util.BitSet? How can I convert it back to an int or long? I'm not so concerned about the size of the BitSet -- it will always be 32 or 64 bits long. I'd just like to use the set(), clear(), nextSetBit(), and nextClearBit() methods rather than bitwise operators, but I can't find an easy way to initialize a bit set with a numeric type.
That sets one single bit with the index you provide. I'd like to set each bit that's set in the integer.
ataylor
2010-03-18 22:17:10
+4
A:
The following code creates a bit set from a long value:
long value = ...;
BitSet bits = new BitSet(Long.SIZE);
int index = 0;
while (value != 0L) {
if (value % 1L != 0) {
bits.set(index);
}
++index;
value = value >>> 1;
}
Arne Burmeister
2010-03-18 22:15:56