Java Utility Library

Java BitSet - toByteArray() Method



The java.util.BitSet.toByteArray() method returns a new byte array containing all the bits in this BitSet.

More precisely, if

byte[] bytes = s.toByteArray();
then, bytes.length == (s.length()+7)/8 and
s.get(n) == ((bytes[n/8] & (1<<(n%8))) != 0)
for all n < 8 * bytes.length
Where s is the given BitSet

Syntax

public byte[] toByteArray()

Parameters

No parameter is required.

Return Value

Returns a byte array containing all the bits in the given BitSet.

Exception

NA.

Example:

In the example below, the java.util.BitSet.toByteArray() method returns a byte array containing all the bits in the given BitSet called BSet.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a BitSet
    BitSet BSet = new BitSet();

    //populating BitSet
    BSet.set(10);
    BSet.set(20);
    BSet.set(30);
    BSet.set(40);
    BSet.set(50); 

    //printing BitSet
    System.out.println("BSet contains: " + BSet);
    
    //convert the BitSet into a byte array
    byte[] Arr = BSet.toByteArray();

    //print the byte array
    System.out.print("Arr contains: ");
    for(byte i: Arr)
      System.out.print(i + " ");
  }
}

The output of the above code will be:

BSet contains: {10, 20, 30, 40, 50}
Arr contains: 0 4 16 64 0 1 4 

❮ Java.util - BitSet