Java Data Type Tutorial - Java BigInteger.toByteArray()








Syntax

BigInteger.toByteArray() has the following syntax.

public byte[] toByteArray()

Example

In the following code shows how to use BigInteger.toByteArray() method.

import java.math.BigInteger;
//from   w  w w.j a v  a2 s.c om
public class Main {

  public static void main(String[] args) {

    // create and assign value to byte array b3
    byte b3[] = { 0x1, 0x00, 0x00 };

    BigInteger bi1 = new BigInteger("10");
    BigInteger bi2 = new BigInteger(b3); // using byte[] constructor of
                                         // BigInteger

    // assign byte array representation of bi1, bi2 to b1, b2
    byte[] b1 = bi1.toByteArray();
    byte[] b2 = bi2.toByteArray();

    for (int i = 0; i < b1.length; i++) {
      System.out.format("0x%02X\n", b1[i]);
    }
    // print byte array b2 using for loop
    for (int j = 0; j < b2.length; j++) {
      System.out.format("0x%02X ", b2[j]);
    }
  }
}

The code above generates the following result.