Java Example - Convert BigInteger to Byte Array or Byte Array to BigInteger

In this blog post, We are going to learn How to Convert ByteArray from/to BigInteger with examples.

You can also check my previous posts on BigInteger class in java.

BigInteger Example

ByteArray is an array of bytes, where each byte represents 8 bits of binary data.

BigInteger is a Java class declared in the java.math package.

Automatic conversion between BigInteger and ByteArray is not available.

In Java, there are use cases where we need to convert BigInteger data to its byte array representation. Each bit represents a value of one or zero, and these are distinct classes with different behaviors.

How to Convert BigInteger to Byte Array in Java?

The BigInteger class provides a toByteArray() method, which returns the byte array of the BigInteger.

This byte array represents the two’s complement representation of the BigInteger value.

Syntax:

public byte[] toByteArray()

It returns two’s complement representation of the byte array value of Biginteger. The returned byte array follows big-endian byte order.

import java.math.BigInteger;
import java.util.Arrays;
public class BigIntegerToByteArrayExample {
 public static void main(String[] args) {
  byte[] bytes = new byte[] { 0x1, 0x20, 0x11 };
  BigInteger bigInteger = new BigInteger(bytes);
  byte byteArray[] = bigInteger.toByteArray();
  System.out.println(Arrays.toString(byteArray));
 }
}

The output of the above code is

[1, 32, 17]

How to Convert Byte Array to BigInteger?

BigInteger has a constructor that accepts a byte array.

public BigInteger(byte[] val)

This constructor converts the byte array, representing a two’s complement binary value, into a BigInteger value.

import java.math.BigInteger;
public class BigIntegerToByteArrayExample {
 public static void main(String[] args) {
  // Negative number
  byte[] bytes = new byte[] {(byte) 0xFF, 0x20, 0x11 };
  BigInteger bigInteger = new BigInteger(bytes);
  System.out.println(bigInteger);
  // Positive number
  byte[] bytes1 = new byte[] {0x1, 0x20, 0x11 };
  BigInteger bigInteger1 = new BigInteger(bytes1);
  System.out.println(bigInteger1);
 }
}

Output is

-57327
73745

Sump up

In summary, we have learned how to convert BigInteger to ByteArray and ByteArray to BigInteger.