I'm looking for a good Java BitSet
example to work with 0 and 1s. I tried looking at the Javadocs but I don't understand the usage of the class by just reading that. For instance, how would the and
, or
, and xor
methods work on two different BitSet
objects?
For example:
BitSet bits1 = new BitSet();
BitSet bits2 = new BitSet();
bits2.set(1000001);
bits1.set(1111111);
bits2.and(bits1);
System.out.println(bits2);
If I do this it returns bits2
as empty why is that?
Try this:
I hope this is useful. For more information, please visit: https://github.com/m-vahidalizadeh/foundations/blob/master/src/data_structures/BitSetExample.java.
I am sharing my implementation for creating a BitSet object using string of bits as input.
For string input "1001"
output :
Here are some links about bitSet that would help you:
UPDATE:
In the docs, it is said:
So when you call
bits2.set(10);
, it is considered as 10 decimal not 1 0 so what you get is the following number1000000000
.To set it correctly, in this example, I want to set the 2nd bit to 1, so I call
bits2.set(1);
because the index starts at 0.In conclusion, for every bit set to 1, you need to call bitSet.Set and provide it with the index of the bit.
If you want to work with bits you can use
int
values in Java 7.prints
For the specific problem you mentioned: when you called
bits2.set(1000001)
, you set the one millionth and first bit to true. Then when you intersected withbits1
, which had the one million, 111 thousand, and 111st bit set, they had no bits in common.I think what you meant to do was
Does this help clear things up?
BitSet doesn't have convenience methods for accepting strings of bits like that. I've provided some below, and now the example works as you'd expect. Note that this uses functionality new in Java 7; it's easy to find implementations of these methods online if you'd like to use Java 6.