user840718 user840718 - 10 days ago 5
Java Question

Java Bitset initialization

I'm using the BitSet class for my program.
I need an inline declaration like:

BitSet bits1 = new BitSet(); //standard declaration
bits1.set(0,2);
bits1.set(4,6);
System.out.println(bits1); //110011

BitSet bits2 = BitSet.valueOf(new long[] {1,1,0,0,1,1}); //inline
System.out.println(bits2);


With this code I'm trying to replicate the same BitSet that is in bits1, in bits2.
The problem is the following: the print and the values are different.
The BitSet I set is 110011. The first one prints out {0, 1, 4, 5} and it is correct since this is the "nice" way to print the BitSet with indexes, the second one prints out{0, 64, 256, 320}.
As you can see the second one is wrong. I'm pretty sure that the inline initialization is wrong, but I cannot figure out how can I fix this.

Answer

Each long in the array represents 64 bits. You only need a single long with 4 bits set:

BitSet bits2 = BitSet.valueOf(new long[] {0b110011});
System.out.println(bits2);
// {0, 1, 4, 5}
Comments