Home > Software design >  Converting Long bitwise operations to BitSet bitwise operations
Converting Long bitwise operations to BitSet bitwise operations

Time:10-22

I'm trying to convert my code from using bitwise operations on Long type to the same operations on a BitSet, but I can't find the right syntax.

This is the original code:

public class BitwiseOperationsWithLong {

    private static final long SETS_OF_BITS_LONG = 141655L;

    //...

    private static int calculate(long setsOfBits) {       
        int counter = 0;
        for (int i = 0; i < 10; i  ) {
            boolean result = ((1L << i) & SETS_OF_BITS_IN_LONG) != 0L;
            if (result) {
                counter  ; 
            }  
    }
    
    return counter;        
}

And this how I try to convert to BitSet:

public class BitwiseOperationsWithBitSet {
    
    private static final String SETS_OF_BITS_STRING = "100010100101010111";
    private static BitSet SETS_OF_BITS_BITSET = bitSetFromString(SETS_OF_BITS_STRING);    

    //...
        
    private static int calculate(BitSet setsOfBits) {       
        int counter = 0;
        for (int i = 0; i < 10; i  ) {
            //the line below is the problematic one
            boolean result = ((1 << i).and(SETS_OF_BITS_IN_LONG)) != 0;
            if (result)
                counter  ;   
        }
        
        return counter;        ​
   ​}

    //method that sets BitSet from String of bits
    private static BitSet bitSetFromString(String binary) {
        BitSet bitset = new BitSet(binary.length());
        for (int i = 0; i < binary.length(); i  ) {
            if (binary.charAt(i) == '1') {
                bitset.set(i);
            }
        }
        return bitset;
    }
}

I can't find the right syntax for this line:

boolean result = ((1 << i).and(SETS_OF_BITS_IN_LONG)) != 0;

I did manage to use the and syntax (instead of &), but I can't find out how to convert the left shift operation part to BitSet. (I am getting The operator & is undefined for the argument type(s) int, BitSet)

CodePudding user response:

When using BitSet you don't need to do the shifting and &ing yourself - the BitSet class has methods for this.

Also you could initialize your BitSet directly from a long constant.

Taking this together your code can look like this:

import java.util.BitSet;

public class BitwiseOperationsWithBitSet {

    private static final long SETS_OF_BITS_LONG = 141655L;
    private static BitSet SETS_OF_BITS_BITSET = BitSet.valueOf(new long[]{SETS_OF_BITS_LONG});

    private static int calculate(BitSet setsOfBits) {       
        int counter = 0;
        for (int i = 0; i < 10; i  ) {
            boolean result = setsOfBits.get(i);
            if (result)
                counter  ;   
        }
        
        return counter;
    }
}
  •  Tags:  
  • java
  • Related