java.math.BigInteger toByteArray()

Description

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
N/A N/A N/A

Method Returns

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

Compatibility

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.

package com.javatutorialhq.java.examples;

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(System.in);
		String input = s.nextLine();		
		s.close();

		// 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();
		System.out.println("result:"+Arrays.toString(result));
		
	}

}

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