In this Blog post, We are going to learn How to Convert BigInteger from/to String with examples. You can also check my previous posts on BigInteger class 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
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
//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");
String s=new String(b);
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!"
Anonymous - Jul 3, 2012
//The following case works without throwing exception BigInteger bigIntegerdemo = new BigInteger(“123”); System.out.println(bigIntegerdemo.toString());
//The following case doest not works and throws NumberFormatException BigInteger bigIntegerdemo1 = new BigInteger(“123”); System.out.println(bigIntegerdemo1.toString());
-————– I could not find any difference 2 blocks of code. Please could you clarify this.