What is BitSet.toByteArray() in Java?

Overview

toByteArray() is an instance method of the BitSet that is used to return the byte array that contains all the bits in the BitSet object.

The toByteArray method is defined in the BitSet class. The BitSet class is defined in the java.util package. To import the BitSet class, use the following import statement.

import java.util.BitSet;

Syntax


public byte[] toByteArray()

Parameters

The method has no parameters.

Return value

The toByteArray method returns a byte array.

Code

import java.util.Arrays;
import java.util.BitSet;
public class Main{
public static void main(String[] args) {
// Create empty BitSet object
BitSet bitSet = new BitSet();
// Set the bit at index 2
bitSet.set(2);
// Get the byte array of the Bitset object using the toByteArray()
System.out.printf("%s.toByteArray() = %s" , bitSet, Arrays.toString(bitSet.toByteArray()));
}
}
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources