Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from BitSet to Byte array

Tags:

java

bitset

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?

like image 769
JavaBits Avatar asked Jun 01 '11 07:06

JavaBits


People also ask

Is BitSet memory efficient?

In addition to throughput, we saw that the BitSet uses much less memory compared to a boolean[] with the same size. To recap, in single-bit read-heavy scenarios, the boolean[] outperforms the BitSet in smaller sizes. However, when the number of bits increases, the BitSet has superior throughput.

Why do we use BitSet?

A BitSet is a very efficient for a set of non-negative integers within a (not too large) range. Much more efficient than arrays and hash maps. An EnumSet is implemented the same way as a BitSet .

How does a BitSet work?

Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1 . All bits are initially false .


2 Answers

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

like image 108
Jon Skeet Avatar answered Oct 04 '22 23:10

Jon Skeet


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

like image 39
Lars Lynch Avatar answered Oct 05 '22 00:10

Lars Lynch