Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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.
–
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
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];
–
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.
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.