I have numbers as 10101, 1000, 11101,.... and so on. I want to store these numbers using bitset class, but dont know how to do that? Please help
3 Answers
There is a BitSet implementation in the standard Java SE API, you should try using that one.
Comments
If you want to use a binary number representation to create a BitSet, this can be done in two steps:
Use the BigInteger constructor that takes a string and a base as arguments. For binary the base is 2.
Initialize a
BitSetfrom the byte array representation of theBigIntegerby calling BigInteger.toByteArray() with BitSet.valueOf().
e.g.
BigInteger a = new BigInteger("10101", 2); //base 2 for binary
BitSet aBits = BitSet.valueOf(a.toByteArray());
BitSet.valueOf() is new in Java 7 so won't work in earlier Java versions.
Edit:
If you don't like initializing BigInteger with strings and your binary numbers fit into 64-bits, you could also use Java 7's binary literals and initialize the BigInteger using BigInteger.valueOf(long) method instead.