小编use*_*er1的帖子

将 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
查看次数

标签 统计

bits ×1

bitset ×1

byte ×1

java ×1