user840718 user840718 - 1 year ago 96
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
System.out.println(bits1); //110011

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

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 Source

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});
// {0, 1, 4, 5}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download