15

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?

1

4 Answers 4

14

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

Sign up to request clarification or add additional context in comments.

Comments

9

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);

Comments

3

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

3 Comments

By the way: the official name is "Java 7" (just as it was since Java 5, but Java 5 was still often called Java 1.5. Java 6 was rarely called Java 1.6).
@Joachim Sauer, Yeah official name Java 7. I just mention the version. Any way thanks to correct me.
Be careful with BitSet.toByteArray() because it may not serialize the bytes in the order you expect. BitSet notEqual = BitSet.valueOf(bitset.toByteArray()); // This doesn't work.
2

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

1 Comment

length also does something else: BitSet bits = new BitSet(16); System.out.println("BITSET LEN=" + bits.size()); gives: BITSET LEN=64 (bit-size of memory used I guess).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.