简体   繁体   English

Java BitSet,可轻松串联BitSet

[英]Java BitSet which allows easy Concatenation of BitSets

I have a need for a BitSet which allows easy concatenation of multiple BitSets create a new BitSet. 我需要一个BitSet,它可以轻松地将多个BitSet串联起来以创建一个新的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. 例如,假设我有一个位数组11111和另一个位数组010101。我想要附加功能。 So after concatenating it would result in 11111010101. 因此,连接后将得到11111010101。

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. 您可以使用明显的nextSetBit进行循环-速度慢,但内存效率高。

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. 大概更快的方法是在一个toLongArray上使用toLongArray ,将其正确复制到足够大的数组中,然后从该数组中创建一个位集,或与另一个数组一起创建一个位集。 That way you don't do any bitshifting on single bits but instead work on wordsized chunks. 这样,您就不会对单个位进行任何移位,而是对字化的块进行处理。

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 结果:11111010101

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM