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