Converting from BitSet to Byte array

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

Tags:

Java

Bitset