BitSet to and from integer/long
Asked Answered
F

7

62

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.

Ferri answered 18/3, 2010 at 21:56 Comment(1)
Personally, I'd say raw bit manipulation is the way to go here. It really isn't that complicated, and as you say I don't see a simple way to get an int or long into a BitSet.Salesperson
N
67

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

Nine answered 18/3, 2010 at 22:15 Comment(2)
FYI, this is creating a bitset in little-endian orderTitled
You should really use BitSet.nextSetBit() for BitSet -> long.Astera
A
50

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];
Africander answered 25/3, 2014 at 18:17 Comment(1)
If the bitset has no "1", bs.toLongArray()[0] will throw ArrayIndexOutOfBoundsException exception!Lianneliao
S
19

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.)

Stout answered 2/2, 2011 at 14:42 Comment(0)
A
5

To get a long back from a small BitSet in a 'streamy' way:

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

Vice-versa:

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

N.B.: Using BitSet::valueOf and BitSet::toLongArray is of course easier.

Astera answered 4/7, 2016 at 13:17 Comment(0)
S
0

Pretty much straight from the documentation of nextSetBit

value=0;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
 value += (1 << i)
 }
Sleuth answered 14/7, 2014 at 22:36 Comment(1)
This will fail for a BitSet larger than 32 or 64 bits, in such a case you'll need to handle an int[] or long[] at the output. But OP explicitly doesn't care, so fair enough. Just a few minor glitches: in case of a long you should 1L << i, to prevent overflow, and an OR like value |= 1L << i is enough.Astera
L
0

For Kotlin those extensions can be used.

BitSet to Int extension:

fun BitSet.toInt() =
    toLongArray()
        .getOrNull(0)
        ?.toInt()
        ?: 0

Int to BitSet extension:

fun Int.toBitSet(size: Int): BitSet {
    val byteArray = byteArrayOf(toByte())

    return BitSet.valueOf(
        if (byteArray.size == size) byteArray
        else byteArray.copyOf(size))
}

Usage example:

val intValue = 1

val bitSetValue = intValue.toBitSet(size = 2)
println("bitSetValue: $bitSetValue")

val firstValue = bitSetValue.get(0)
println("firstValue: $firstValue")

val secondValue = bitSetValue.get(1)
println("secondValue: $secondValue")

bitSetValue.set(0, true)
bitSetValue.set(1, false)
println("bitSetValue: $bitSetValue")

val newIntValue = bitSetValue.toInt()
println("newIntValue: $newIntValue")
Laddy answered 6/6, 2023 at 5:16 Comment(0)
S
-3

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

Syzran answered 18/3, 2010 at 22:9 Comment(1)
That sets one single bit with the index you provide. I'd like to set each bit that's set in the integer.Ferri

© 2022 - 2024 — McMap. All rights reserved.