BitSet to and from integer/long

Solution 1:

The following code creates a bit set from a long value and vice versa:

public class Bits {

  public static BitSet convert(long value) {
    BitSet bits = new BitSet();
    int index = 0;
    while (value != 0L) {
      if (value % 2L != 0) {
        bits.set(index);
      }
      ++index;
      value = value >>> 1;
    }
    return bits;
  }

  public static long convert(BitSet bits) {
    long value = 0L;
    for (int i = 0; i < bits.length(); ++i) {
      value += bits.get(i) ? (1L << i) : 0L;
    }
    return value;
  }
}

EDITED: Now both directions, @leftbrain: of cause, you are right

Solution 2:

Add to finnw answer: there are also BitSet.valueOf(long[]) and BitSet.toLongArray(). So:

int n = 12345;
BitSet bs = BitSet.valueOf(new long[]{n});
long l = bs.toLongArray()[0];

Solution 3:

Java 7 has BitSet.valueOf(byte[]) and BitSet.toByteArray()

If you are stuck with Java 6 or earlier, you can use BigInteger if it is not likely to be a performance bottleneck - it has getLowestSetBit, setBit and clearBit methods (the last two will create a new BigInteger instead of modifying in-place.)