Open In App

BigInteger toByteArray() Method in Java

Last Updated : 18 Apr, 2023
Suggest changes
Share
Like Article
Like
Report

The java.math.BigInteger.toByteArray() method returns an array of bytes containing the two's-complement representation of this BigInteger. The most significant byte of the byte array is present in the zeroth element. The returning array from this method contains sign bit and 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 accept any parameters. 

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

The 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()


Explore