Reputation: 6328
I am looking for a way to add two BitSet. Should i go to the basics of binary number and perform XOR
and AND
operation over BitSet. As basic says here-
Will this be efficient?
Upvotes: 5
Views: 3614
Reputation: 726579
No, it wouldn't be efficient, because you wouldn't know the carry for bit N
until you've processed all bits through N-1
. This is the problem solved by carry look-ahead adders in hardware.
There is no way to implement addition of BitSets in a way that does not involve examining all their bits one-by-one in the worst case. An alternative strategy depends a lot on your specific requirements: if you mutate your bit sets a lot, you may want to roll your own, based on Sun's Oracle's implementation. You can shamelessly copy borrow their code, and add an implementation of add
that operates on the "guts" of the BitSet
, stored as long[] bits
. You'll need to be very careful dealing with overflows (remember, all numbers in Java are signed), but otherwise it should be rather straightforward.
Upvotes: 4
Reputation: 9608
The most efficient way would be to convert both bitsets to numbers and just add them
Upvotes: 1