BitSet with integer and duration

If I have an integer for which I would like to process bits, how can I load it in java.util.BitSet ? How can I convert it back to int or long? I don't care about the size of the BitSet - it will always be 32 or 64 bits. I would just like to use the set() , clear() , nextSetBit() and nextClearBit() , rather than bitwise operators, but I cannot find an easy way to initialize a bit set using a numeric type.

+42
java bit-manipulation bitset
Mar 18 '10 at 21:56
source share
6 answers

The following code creates a bit 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: reason, you're right

+47
Mar 18 '10 at 22:15
source share
— -

Add the answer to finnw: 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]; 
+21
Mar 25 '14 at 18:17
source share

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

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

+17
Feb 02 2018-11-14T00:
source share

To get long back from small BitSet in BitSet :

 long l = bitSet.stream() .takeWhile(i -> i < Long.SIZE) .mapToLong(i -> 1L << i) .reduce(0, (a, b) -> a | b); 

And vice versa:

 BitSet bitSet = IntStream.range(0, Long.SIZE - 1) .filter(i -> 0 != (l & 1L << i)) .collect(BitSet::new, BitSet::set, BitSet::or); 

NB: Using BitSet::valueOf and BitSet::toLongArray is certainly simpler.

+3
Jul 04 '16 at 13:17
source share

Pretty much of nextSetBit documentation

 value=0; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { value += (1 << i) } 
+1
Jul 14 '14 at 22:36
source share

Not the public void set(int bit) method, what are you looking for?

-2
Mar 18
source share



All Articles