Converting a BigInteger to a byte array

Use the method toByteArray. The length of that byte array returned is based on the number of significant bits + a sign bit.
The most significant bit will be in array element 0.

Main.java:

import java.math.*;
  
public class Main {
   public static void main(String args[]) {
      BigInteger bi = new BigInteger("123456789");
 
      byte[] bArray = bi.toByteArray();
 
      NumberFormat nf = NumberFormat.getInstance();
      for (int i=0; i<bArray.length; i++) {
         System.out.println(format(Integer.toBinaryString((int) bArray[i]), 8));
      }
 
      System.out.println("should be equal to: ");
      System.out.println(format(Integer.toBinaryString(123456789), 32));
   } 
 
   public static String format(String s, int nBits) {
      if (s.length() > nBits) return s.substring(s.length()-nBits);
  
      StringBuffer temp = new StringBuffer();
      for (int i=0; i<nBits-s.length(); i++) temp.append('0');
      temp.append(s);
      return temp.toString();
   }
}

outputs:

00000111
01011011
11001101
00010101
should be equal to: 
00000111010110111100110100010101