java.math.BigInteger toByteArray()


On this document we will be showing a java example on how to use the toByteArray() method of BigInteger Class. Basically this method returns a byte array containing the two’s-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)). (This representation is compatible with the (byte[]) constructor.)


Method Syntax

public byte[] toByteArray()

Method Argument

Data Type Parameter Description

Method Returns

The toByteArray() method returns a byte array containing the two’s-complement representation of this BigInteger.


Requires Java 1.1 and up

Java BigInteger toByteArray() Example

Below is a java code demonstrates the use of toByteArray() method of BigInteger class. The example presented might be simple however it shows the behavior of the toByteArray() method.


import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;

 * A java example source code to demonstrate
 * the use of toByteArray() method of BigInteger class

public class BigIntegerToByteArrayExample {

	public static void main(String[] args) {	
		// get user input
		System.out.print("Enter a value:");
		Scanner s = new Scanner(;
		String input = s.nextLine();		

		// convert the first String Input to BigInteger
		BigInteger val1 = new BigInteger(input);
		 * get the the byte array equivalent of the user input
		byte[] result = val1.toByteArray();


This example is a lot simpler than it looks. Basically we ask for user input and converted this value into BigInteger. We then printed out the results of the toByteArray() operation using the Arrays.toString method.

Sample Output

Below is the sample output when you run the above example.

BigInteger toByteArray() example output