相关疑难解决方法(0)

BitSet与整数/长整数

如果我有一个我想要执行位操作的整数,我该如何将其加载到java.util.BitSet?如何将其转换回int或long?我不太关心BitSet它的大小- 它总是32或64位长.我只是想使用set(),clear(),nextSetBit(),和nextClearBit()方法,而不是位运算符,但我无法找到一个简单的方法来初始化位以数字类型设置.

java bit-manipulation bitset

52
推荐指数
4
解决办法
6万
查看次数

将 byte[] 转换为 BitSet

我正在尝试将字节数组转换为 BitSet。以下是我正在使用的代码:

public BitSet byteToBits(byte[] bytearray){
    BitSet returnValue = new BitSet(bytearray.length*8);
    ByteBuffer  byteBuffer = ByteBuffer.wrap(bytearray);
    //System.out.println(byteBuffer.asIntBuffer().get(1));
    //Hexadecimal values used are Big-Endian, because Java is Big-Endian
    for (int i = 0; i < bytearray.length; i++) {
        byte thebyte = byteBuffer.get(i);
        for (int j = 0; j <8 ; j++) {
            returnValue.set(i*8+j,isBitSet(thebyte,j));
        }
    }
    return returnValue;
}

private static Boolean isBitSet(byte b, int bit)
{
    return (b & (1 << bit)) != 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 JUnit 测试对其进行测试,如下所示。

@org.junit.Test
public void byteToBits() throws …
Run Code Online (Sandbox Code Playgroud)

java byte bits bitset

3
推荐指数
1
解决办法
6862
查看次数

标签 统计

bitset ×2

java ×2

bit-manipulation ×1

bits ×1

byte ×1