简体   繁体   中英

Converting BitSet to Byte[]

I have a BitSet, which needs to be converted to a Byte[]. However, by using BitSet.toByteArray(), I don't get the correct output. 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.

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. Why is this happening, and how can I fix it?

From 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 .

@return a byte array containing a little-endian representation of all the bits in this bit set

@since 1.7

Attention: toByteArray() doesn't even claim to know size() , it is only "reliable" regarding length() !


..So I would propose as implementation (alternative for your toBinaryString() ) a method like:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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