繁体   English   中英

将byte []转换为BitSet

[英]Convert byte[] to 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;
}

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

@org.junit.Test
public void byteToBits() throws Exception {
    byte[] input = new byte[]{(byte) 0b1011_1011};
    BitSet expectedOutput = new BitSet(8);
    expectedOutput = BitSet.valueOf(new byte[]{(byte)0b1011_1011});
    assertEquals(expectedOutput,converter.byteToBits(input));
    assertEquals(expectedOutput.toByteArray(),input);
}

@Test
public void testBytestoBitslength() throws Exception {
    byte[] input = new byte[]{(byte) 0xFFFF,(byte)0x7F70,(byte)0xF45A,(byte)0xA24B};
    BitSet output = converter.byteToBits(input);
    System.out.println("byte[] length: "+input.length+ "x8: "+input.length*8);
    System.out.println("BitSet length: "+output.length());
    System.out.println(input.toString());
    System.out.println(output.toByteArray().toString());
    assertTrue(output.length()==input.length*8);
}

这段代码虽然没有通过测试,但我不明白为什么。

对于byteToBits:

java.lang.AssertionError: 
Expected :[B@6438a396
Actual   :[B@e2144e4

对于testBytestoBitslength:

byte[] length: 4x8: 32
BitSet length: 31
[B@4f2410ac
[B@722c41f4

尝试用BitSet.valueOf(byte [])方法调用替换它。 它仍然失败,尽管更有趣。

@Test
public void curiosity() throws Exception {
    byte[] byteArray = new byte[]{1, 2, 3};
    BitSet bitSet = BitSet.valueOf(byteArray);
    System.out.println("byte[]: "+byteArray);
    System.out.println(bitSet.toByteArray());
    assertEquals(ByteBuffer.wrap(byteArray),ByteBuffer.wrap(bitSet.toByteArray()));
    assertEquals(bitSet.length(),byteArray.length*8);
}

这将返回以下内容:

byte[]: [B@6438a396
BitSet: [B@e2144e4

java.lang.AssertionError: 
Expected :18
Actual   :24

当由ByteBuffer包装时,两个对象返回相同的东西,但它们看起来完全不同,并且这两个对象具有不同的长度。

要将字节转换为BitSet,您应该尝试

final byte b = ...;
final BitSet set = BitSet.valueOf(new byte[] { b });

您可以参考将byte或int转换为bitset,它可能会对您有所帮助。

一个人无法直接比较两个byte[]数组,因为byte[] s不能实现可比性。 这里的解决方案是将它们包装在ByteBuffer中,如@PaulBoddington所建议的那样。

assertEquals(ByteBuffer.wrap(expectedOutput.toByteArray()),ByteBuffer.wrap(input));

另一个长度问题是由BitSet本身引起的。 BitSet.length()返回从BitSetBitSet最后一个设置位的长度,这会导致BitSet.length()byte[].length*8 BitSet.length() byte[].length*8的长度不一致。 这里唯一的解决方案是使用BitSet.toByteArray().length*8 ,这里需要BitSet.length()

暂无
暂无

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

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