BitSet toByteArray() Method in Java with Examples

Last Updated : 27 Dec, 2018
The java.util.BitSet.toByteArray() is an inbuilt method of BitSet class that is used to produce a new byte array containing all of the bits of the existing BitSet. As per the official documentation, this process works in the following way:
if, byte[] bytes = bit_set.toByteArray(); then, bytes.length == (bit_set.length()+7)/8 and, bit_set.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)
For all n < 8 * bytes.length
Syntax:
Bit_Set.toByteArray()
Parameter: The method does not take any parameters. Return value: The method returns the set consisting of ByteArray representation of the elements of the given BitSet. Below programs illustrate the working of java.util.BitSet.toByteArray() method: Program 1: Java
// Java code to illustrate toByteArray()
import java.util.*;

public class BitSet_Demo {
    public static void main(String args[])
    {
        // Creating an empty BitSet
        BitSet init_bitset = new BitSet();

        // Use set() method to add elements into the Set
        init_bitset.set(10);
        init_bitset.set(20);
        init_bitset.set(30);
        init_bitset.set(40);
        init_bitset.set(50);

        // Displaying the BitSet
        System.out.println("BitSet: " + init_bitset);

        byte[] arr = init_bitset.toByteArray();
        System.out.println("The byteArray is: " + arr);

        // Displaying the byteArray
        System.out.println("The elements in the byteArray :");
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + ", ");
    }
}
Output:
BitSet: {10, 20, 30, 40, 50}
The byteArray is: [B@232204a1
The elements in the byteArray :
0, 4, 16, 64, 0, 1, 4,
Program 2: Java
// Java code to illustrate toByteArray()
import java.util.*;

public class BitSet_Demo {
    public static void main(String args[])
    {
        // Creating an empty BitSet
        BitSet init_bitset = new BitSet();

        // Use set() method to add elements into the Set
        init_bitset.set(48);
        init_bitset.set(64);
        init_bitset.set(15);
        init_bitset.set(95);
        init_bitset.set(105);
        init_bitset.set(21);

        // Displaying the BitSet
        System.out.println("BitSet: " + init_bitset);

        byte[] arr = init_bitset.toByteArray();
        System.out.println("The byteArray is: " + arr);

        // Displaying the byteArray
        System.out.println("The elements in the byteArray :");
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + ", ");
    }
}
Output:
BitSet: {15, 21, 48, 64, 95, 105}
The byteArray is: [B@232204a1
The elements in the byteArray :
0, -128, 32, 0, 0, 0, 1, 0, 1, 0, 0, -128, 0, 2,
Comment