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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The following code creates a bit set from a long value and vice versa:
EDITED: Now both directions, @leftbrain: of cause, you are right
Pretty much straight from the documentation of nextSetBit
Isn't the
public void set(int bit)
method what your looking for?To get a
long
back from a smallBitSet
in a 'streamy' way:Vice-versa:
N.B.: Using
BitSet::valueOf
andBitSet::toLongArray
is of course easier.Java 7 has
BitSet.valueOf(byte[])
andBitSet.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 hasgetLowestSetBit
,setBit
andclearBit
methods (the last two will create a newBigInteger
instead of modifying in-place.)Add to finnw answer: there are also
BitSet.valueOf(long[])
andBitSet.toLongArray()
. So: