Java BitSet toByteArray() method

The toByteArray() method of Java BitSet class returns a new byte array which contains all of its bits.

This method works on the basis of following algorithm:

for all n < 8 * bytes.length.

Syntax:

Parameter:

NA

Returns:

This method returns a byte array which contains all the bits of this bit set.

Exception:

NA

Compatibility Version:

Java 1.7 and above

Example 1

Output:

bitset: {0, 1, 3, 5, 6}
byte array: 107

Example 2

Each byte array of the BitSet is set is the interval of each byte (8 bit) space. The length of a byte space increases if the set bit is set above the previous byte size.

In this example, the set bits from index 0 to 6 are placed in the first byte bit space and the set bit from index 8 and 9 are placed at second byte.

Output:

bitset: {0, 1, 3, 5, 6, 8, 9}
byte array1: 107
byte array2: 3