BigInteger toByteArray() Method in Java
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
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
BigInteger bigInt = BigInteger.valueOf( 10 );
byte b1[];
b1 = bigInt.toByteArray();
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
import java.math.BigInteger;
public class GFG {
public static void main(String[] args)
{
byte b[] = { 0x1 , 0x2 , 0x1 };
BigInteger bigInt = new BigInteger(b);
byte b1[] = bigInt.toByteArray();
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()
Last Updated :
18 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...