Parsing and Formatting a Big Integer into Binary in Java

Java 8Object Oriented ProgrammingProgramming

Firstly, take two BigInteger objects and set values.

BigInteger one, two;
one = new BigInteger("99");
two = new BigInteger("978");

Now, parse BigInteger object “two” into Binary.

two = new BigInteger("1111010010", 2);
String str = two.toString(2);

Above, we have used the following constructor. Here, radix is set as 2 for Binary for both BigInteger constructor and toString() method.

BigInteger(String val, int radix)

This constructor is used to translate the String representation of a BigInteger in the specified radix into a BigInteger.

The following is an example −

Example

 Live Demo

import java.math.*;
public class Demo {
   public static void main(String[] args) {
      BigInteger one, two;
      one = new BigInteger("99");
      // parsing BigInteger object "two" into Binary
      two = new BigInteger("1111010010", 2);
      String str = two.toString(2);
      System.out.println("Result (BigInteger) : " +one);
      System.out.println("Result after parsing : " +str);
   }
}

Output

Result (BigInteger) : 99
Result after parsing : 1111010010
raja
Published on 20-Dec-2018 10:18:32
Advertisements