10

I have a need for a BitSet which allows easy concatenation of multiple BitSets create a new BitSet. The default implementation doesn't have such a method.

Is there any an implementation in some external library that any of you know which allows easy concatenation?

For example lets say I have a bitarray 11111 and another bit array 010101. I want functionality like appending. So after concatenating it would result in 11111010101.

Can't Tell
  • 12,714
  • 9
  • 63
  • 91
  • 2
    Since a BitSet has no meaningful size or length (except the highest set bit), it is a little bit difficult to understand what you mean with concatenation. – jarnbjo May 08 '12 at 09:37
  • @jarnbjo I edited the question. Hope it makes sense now. – Can't Tell May 08 '12 at 09:51
  • 2
    That's not 'concatenation'. That is left-shifting and OR-ing. I doubt you will be able to come up with a coherent definition of your version of concatenation. For example why observe the one leading zero in `010101` in your example, and ignore the infinity of other leading zeros? – user207421 May 08 '12 at 11:10
  • @EJP I know the size of a given bit string. – Can't Tell May 08 '12 at 12:06
  • @Can'tTell No you don't. Once it gets into a BitSet there are no leading zeroes. – user207421 May 08 '12 at 13:02

2 Answers2

5

Well there's no way to implement this terribly efficient (performance and memory that is) since there's no leftshift method.

What you can do is either use the obvious nextSetBit for loop - slow, but memory efficient.

The presumably faster method would be to use toLongArray on one, copy that correctly shifted into a large enough array, create a bitset from that and or it with the other. That way you don't do any bitshifting on single bits but instead work on wordsized chunks.

Voo
  • 29,040
  • 11
  • 82
  • 156
1

This worked for me:

BitSet concatenate_vectors(BitSet vector_1_in, BitSet vector_2_in) {
  BitSet vector_1_in_clone = (BitSet)vector_1_in.clone();
  BitSet vector_2_in_clone = (BitSet)vector_2_in.clone();
  int n = 5;//_desired length of the first (leading) vector
  int index = -1;
  while (index < (vector_2_in_clone.length() - 1)) {
    index = vector_2_in_clone.nextSetBit((index + 1));
    vector_1_in_clone.set((index + n));
  }
  return vector_1_in_clone;
}

Result: 11111010101