Converting Between a BitSet and a Byte Array

There are no default methods for converting a BitSet to and from a byte array. This example implements two methods to do the conversion. These methods make it possible to easily work with both BitSet and BigInteger and take advantage of their capabilities when needed.
// Returns a bitset containing the values in bytes. // The byte-ordering of bytes must be big-endian which means the most significant bit is in element 0. public static BitSet fromByteArray(byte[] bytes) { BitSet bits = new BitSet(); for (int i=0; i<bytes.length*8; i++) { if ((bytes[bytes.length-i/8-1]&(1<<(i%8))) > 0) { bits.set(i); } } return bits; } // Returns a byte array of at least length 1. // The most significant bit in the result is guaranteed not to be a 1 // (since BitSet does not support sign extension). // The byte-ordering of the result is big-endian which means the most significant bit is in element 0. // The bit at index 0 of the bit set is assumed to be the least significant bit. 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; }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.