简体   繁体   English

将BitSet转换为Byte []

[英]Converting BitSet to Byte[]

I have a BitSet, which needs to be converted to a Byte[]. 我有一个BitSet,需要将其转换为Byte []。 However, by using BitSet.toByteArray(), I don't get the correct output. 但是,通过使用BitSet.toByteArray(),我没有得到正确的输出。 I have tried converting the Byte[] to its binary form in order to check whether the Bitset and the binary form of the Byte[] are similiar. 我已尝试将Byte []转换为其二进制形式,以检查Byte []的位集和二进制形式是否相似。

public static void generate() {

        BitSet temp1 = new BitSet(64);

        for (int i = 0; i < 64; i++) {
            if(i % 8 != 0 && i < 23) {
            temp1.set(i, true);
            }
        }

        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 64; i++) {
            s.append(temp1.get(i) == true ? 1 : 0);
        }

        System.out.println(s);

        byte[] tempByteKey1 = temp1.toByteArray();

        for (byte b : tempByteKey1) {
            System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
        }

    }

Output: 输出:

Bitset: 0111111101111111011111100000000000000000000000000000000000000000
Converted Byte: 1111111011111110011111100000000000000000000000000000000000000000

They are both 64 bits, but the first 0 in the BitSet is placed somewhere else after the conversion. 它们都是64位,但是BitSet中的第一个0放置在转换后的其他位置。 Why is this happening, and how can I fix it? 为什么会发生这种情况,我该如何解决?

From BitSet#toByteArray() javadoc : BitSet#toByteArray()javadoc

Returns a new byte array containing all the bits in this bit set. 返回一个新的字节数组,其中包含该位集中的所有位。 More precisely, if.. 更确切地说,如果

byte[] bytes = s.toByteArray();

then 然后

bytes.length == (s.length()+7)/8

and

s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)

for all n < 8 * bytes.length . 对于所有n < 8 * bytes.length

@return a byte array containing a little-endian representation of all the bits in this bit set @返回一个字节数组,其中包含该位集中所有位的小端序表示

@since 1.7 @ 1.7起

Attention: toByteArray() doesn't even claim to know size() , it is only "reliable" regarding length() ! 注意: toByteArray()甚至不声称知道size() ,对于length() ,这只是“可靠的”!


..So I would propose as implementation (alternative for your toBinaryString() ) a method like: ..因此,我建议将以下方法作为实现(作为toBinaryString()替代方法):

static String toBinaryString(byte[] barr, int size) {
    StringBuilder sb = new StringBuilder();
    int i = 0;
    for (; i < 8 * barr.length; i++) {
        sb.append(((barr[i / 8] & (1 << (i % 8))) != 0) ? '1' : '0');
    }
    for (; i < size; i++) {
        sb.append('0');
    }
    return sb.toString();
}

..to call it like: ..像这样称呼它:

System.out.println(toBinaryString(bitSet.toByteArray(), 64);

run:
0111111101111111011111100000000000000000000000000000000000000000
0111111101111111011111100000000000000000000000000000000000000000
BUILD SUCCESSFUL (total time: 0 seconds)

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

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