Reputation: 2055
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?
Upvotes: 15
Views: 19176
Reputation: 2153
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
Upvotes: 2
Reputation: 291
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);
Upvotes: 10
Reputation: 2209
This works fine for me. if you are using Java 1.7 then it has the method toByteArray()
.
Upvotes: 3
Reputation: 1500055
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."
Upvotes: 15