Saturday, September 1, 2018

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

Java Example - Convert BigInteger to/from Byte Array
In this Blog post, We are going to learn How to Convert Integer/int from/to Biginteger with examples. You can also check my previous posts on BigInteger class in java

BigInteger Example

Byte Array is an array of bytes. Each byte is 8 bits of binary data. 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

BigInteger is a java class declared in java.math package. There is no automatic conversion BigInteger and Byte Array as this are different classes with different behaviors.

How to Convert BigInteger to Byte Array

BigInteger class has toByteArray() method return the byte array of big integer two's complement representation of bit integer value.
Syntax
public byte[] toByteArray()
This returns two's complement representation of the byte array value of Biginteger. Returned bye 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]

Convert Byte Array to BigInteger

 BigInteger has a constructor which we can supply 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

Related article


EmoticonEmoticon