Get byte array from BigInteger in Java

Java 8Object Oriented ProgrammingProgramming

First, set the BigInteger object with binary.

BigInteger val = new BigInteger("100000000110001100000", 2);

Now, use the toByteArray() method.

byte[] byteArr = val.toByteArray();

The following is an example −

Example

 Live Demo

import java.math.BigInteger;
public class Demo {
   public static void main(String[] argv) throws Exception {
      BigInteger val = new BigInteger("100000000110001100000", 2);
      byte[] byteArr = val.toByteArray();
      for (int i = 0; i < byteArr.length; i++) {
         System.out.format("0x%02X\n", byteArr[i]);
      }
   }
}

Output

0x10
0x0C
0x60
raja
Published on 20-Dec-2018 15:29:12
Advertisements