BigInteger toByteArray() Method in Java

The java.math.BigInteger.toByteArray() method returns a array of byte containing the two’s-complement representation of this BigInteger. The most significant byte of byte array is present in the zeroth element. The returning array from this method contain sing bit and conntain the minimum number of bytes required to represent this BigInteger. The sign bit position is (ceil((this.bitLength() + 1)/8)).

Syntax:

public byte[] toByteArray()

Parameters: This method does not accepts any parameters.



Return Value: This method returns a byte array containing the two’s-complement representation of this BigInteger.

Below programs illustrate toByteArray() method of BigInteger class:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate toByteArray() method of BigInteger
  
import java.math.BigInteger;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Creating BigInteger object
        BigInteger bigInt = BigInteger.valueOf(10);
  
        // create a byte array
        byte b1[];
        b1 = bigInt.toByteArray();
  
        // print result
        System.out.print("ByteArray of BigInteger "
                         + bigInt + " is");
  
        for (int i = 0; i < b1.length; i++) {
            System.out.format(" "
                                  + "0x%02X",
                              b1[i]);
        }
    }
}

chevron_right


Output:

ByteArray of BigInteger 10 is 0x0A

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate toByteArray() method of BigInteger
  
import java.math.BigInteger;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // create byte array
        byte b[] = { 0x1, 0x2, 0x1 };
  
        // Creating BigInteger object using byte Array
        BigInteger bigInt = new BigInteger(b);
  
        // apply toByteArray() on BigInteger
        byte b1[] = bigInt.toByteArray();
  
        // print result
        System.out.print("ByteArray of BigInteger "
                         + bigInt + " is");
  
        for (int i = 0; i < b1.length; i++) {
            System.out.format(" "
                                  + "0x%02X",
                              b1[i]);
        }
    }
}

chevron_right


Output:

ByteArray of BigInteger 66049 is 0x01 0x02 0x01

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#toByteArray()



My Personal Notes arrow_drop_up

I am a Developer I love to code and bring my ideas alive

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.