views:

418

answers:

2

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.

A: 

Isn't the public void set(int bit) method what your looking for?

kukudas
That sets one single bit with the index you provide. I'd like to set each bit that's set in the integer.
ataylor
+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
I think the line (value % 1L != 0) should be (value % 2L != 0)
leftbrainlogic