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. Each byte is 8 bits of binary data.

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

There is no automatic conversion BigInteger and Byte Array.

In Java, We used to have use cases like where we need to convert Biginteger data to its bytes of array data. Each bit represents the value of one or zero are different classes with different behavior.

How to Convert BigInteger to Byte Array in java?

BigInteger class has toByteArray() method return the byte array of big integer which is equal to two’s complement representation of bit integer value.

Syntax:

public byte[] toByteArray()

It returns two’s complement representation of the byte array value of Biginteger. Returned byte array order 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 byte array to it.

public BigInteger(byte[] val)

Convert the byte array in 2’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

To summary, We learned how to convert BigInteger to ByteArray and ByteArray to BigInteger.