繁体   English   中英

将 Long 按位运算转换为 BitSet 按位运算

[英]Converting Long bitwise operations to BitSet bitwise operations

我试图将我的代码从在 Long 类型上使用按位操作转换为在 BitSet 上使用相同的操作,但我找不到正确的语法。

这是原始代码:

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;        
}

这就是我尝试转换为 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;
    }
}

我找不到这一行的正确语法:

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

我确实设法使用and语法(而不是& ),但我不知道如何将左移操作部分转换为 BitSet。 (我得到The operator & is undefined for the argument type(s) int, BitSet

使用BitSet您不需要自己进行移位和& - BitSet类具有用于此的方法。

您也可以直接从长常量初始化BitSet

将这些放在一起,您的代码可能如下所示:

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;
    }
}

暂无
暂无

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

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