Skip to content
Related Articles
Open in App
Not now

Related Articles

BigInteger toByteArray() Method in Java

Improve Article
Save Article
  • Last Updated : 12 Apr, 2022
Improve Article
Save Article

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 contain 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: 

Java




// 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]);
        }
    }
}


Output:

ByteArray of BigInteger 10 is 0x0A

Example 2: 

Java




// 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]);
        }
    }
}


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
Related Articles

Start Your Coding Journey Now!