Monday, December 26, 2011

How to Convert BigInteger to String or String to BigInteger in java with examples?

BigInteger Object in Java

Conversion of BigInteger to String is one of the days to day task for java programmer. A few days back I have the need to convert the BigInteger to Integer in my programming. It is a simple task to do the same.
BigInteger is commonly used for storing the numerical big values by the result of arbitrary arithmetic calculations. The value stored in BigInteger is higher than all primitive data type values. No Upper limit the maximum value that can store in a big integer.In My Previous Post, we have discussed the conversion of BigInteger to Integer or vice verse. we can also do the same for conversion to String

We have two cases 1. BigInteger to String 2. String to BigInteger

How to Covert BigInteger to a String object in Java:-

We can do this in many ways
Using toString() method

One of the way is to use the BigInteger.toString() method or String.valueOf() in java.This is a simple coding task to do.BigInteger class constructor for passing String as a parameter for BigInteger object creation

BigInteger bi=new BigInteger("123");

As you know every java class has toString method, To return the String object with for the BigInteger class.Following is the line of code for returning String object

String str=bi.toString();

//The following case works without throwing exception
  BigInteger bigIntegerdemo = new BigInteger("123");

  //The following case doest not works and throws NumberFormatException
  BigInteger bigIntegerdemo1 = new BigInteger("123");

The disadvantages with this approach are always we need to pass the numeric value in the form of String for BigInteger constructor.
if String like "abc" is passed, it throws NumberFormatException.
using toByteArray() method
The other way around to conversion to String is first to convert the BigInteger object to bytes using toByteArray() method and then passing array bytes to String's byte Constructor

BigInteger bigIntegerdemo2 = new BigInteger("123");
  byte b[]=bigIntegerdemo2.toByteArray();
  String s=new String(b);

How to Convert String to a BigInteger object in Java:-

Another way around is to use the BigInteger.toByteArray()
In this process, we are converting String to an array of bytes using String.getBytes() method and then Bytes to BigInteger using toByteArray() method.
String msg = new String ("Hi Techrocksz!");
  BigInteger bi = new BigInteger(msg.getBytes());
  System.out.println(new String(bi.toByteArray())); // prints "Hi Techrocksz!"

Hope you understand this. Please leave a comment if there are any more ways to convert this.



Note: Only a member of this blog may post a comment.