OR operation in Java(BitSet.class)

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 13:35:13

This should work (update: bug fixed):

public static BitSet or(final String... args){
    final BitSet temp = createBitset(args[0]);
    for(int i = 1; i < args.length; i++){
        temp.or(createBitset(args[i]));
    }
    return temp;
}

private static BitSet createBitset(final String input){
    int length = input.length();
    final BitSet bitSet = new BitSet(length);
    for(int i = 0; i < length; i++){
        // anything that's not a 1 is a zero, per convention
        bitSet.set(i, input.charAt(length - (i + 1)) == '1');
    }
    return bitSet;
}

Sample code:

public static void main(final String[] args){
    final BitSet bs =
        or("01010101", "10100000", "00001010", "1000000000000000");
    System.out.println(bs);
    System.out.println(toCharArray(bs));
}

private static char[] toCharArray(final BitSet bs){
    final int length = bs.length();
    final char[] arr = new char[length];
    for(int i = 0; i < length; i++){
        arr[i] = bs.get(i) ? '1' : '0';
    }
    return arr;
}

Output:

{0, 1, 2, 3, 4, 5, 6, 7, 15}
1111111100000001

Can't you just call the or method in the BitSet class?

[edit] Assuming you wanted an example, something like this should work:

BitSet doOr( List<BitSet> setsToOr ) {
  BitSet ret = null ;
  for( BitSet set : setsToOr ) {
    if( ret == null ) {
      // Set ret to a copy of the first set in the list
      ret = (BitSet)set.clone() ;
    }
    else {
      // Just or with the current set (changes the value of ret)
      ret.or( set ) ;
    }
  }
  // return the result
  return ret ;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!