简体   繁体   中英

Converting from BitSet to Byte array

I have picked up this example which converts BitSet to Byte array.

public static byte[] toByteArray(BitSet bits) {
    byte[] bytes = new byte[bits.length()/8+1];
    for (int i=0; i<bits.length(); i++) {
        if (bits.get(i)) {
            bytes[bytes.length-i/8-1] |= 1<<(i%8);
        }
    }
    return bytes;
}

But in the discussion forums I have seen that by this method we wont get all the bits as we will be loosing one bit per calculation. Is this true? Do we need to modify the above method?

No, that's fine. The comment on the post was relating to the other piece of code in the post, converting from a byte array to a BitSet . I'd use rather more whitespace, admittedly.

Also this can end up with an array which is longer than it needs to be. The array creation expression could be:

byte[] bytes = new byte[(bits.length() + 7) / 8];

This gives room for as many bits are required, but no more. Basically it's equivalent to "Divide by 8, but always round up."

If you need the BitSet in reverse order due to endian issues, change:

bytes[bytes.length-i/8-1] |= 1<<(i%8);

to:

bytes[i/8] |= 1<<(7-i%8);

This works fine for me. if you are using Java 1.7 then it has the method toByteArray() .

FYI, using

bits.length()

to fetch the size of the bitset may return incorrect results; I had to modify the original example to utilize the size() method to get the defined size of the bitset (whereas length() returns the number of bits set). See the thread below for more info.

java.util.BitSet -- set() doesn't work as expected

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