Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BigInteger to String in java

I converted a String to BigInteger as follows:

Scanner sc=new Scanner(System.in); System.out.println("enter the message"); String msg=sc.next(); byte[] bytemsg=msg.getBytes(); BigInteger m=new BigInteger(bytemsg);  

Now I want my string back. I'm using m.toString() but that's giving me the desired result.

Why? Where is the bug and what can I do about it?

like image 980
condinya Avatar asked Jun 12 '10 10:06

condinya


People also ask

How do you get BigInteger from String?

One way is to use the BigInteger(String value, int radix) constructor: String inputString = "290f98"; BigInteger result = new BigInteger(inputString, 16); assertEquals("2690968", result. toString()); In this case, we're specifying the radix, or base, as 16 for converting hexadecimal to decimal.

Can we convert BigInteger to integer in Java?

The java. math. BigInteger. intValue() converts this BigInteger to an integer value.

What is radix in Java BigInteger?

The java. math. BigInteger. toString(int radix) returns the String representation of this BigInteger in the given radix. If the radix is outside the range from Character.


2 Answers

You want to use BigInteger.toByteArray()

String msg = "Hello there!"; BigInteger bi = new BigInteger(msg.getBytes()); System.out.println(new String(bi.toByteArray())); // prints "Hello there!" 

The way I understand it is that you're doing the following transformations:

  String  -----------------> byte[] ------------------> BigInteger           String.getBytes()         BigInteger(byte[]) 

And you want the reverse:

  BigInteger ------------------------> byte[] ------------------> String              BigInteger.toByteArray()          String(byte[]) 

Note that you probably want to use overloads of String.getBytes() and String(byte[]) that specifies an explicit encoding, otherwise you may run into encoding issues.

like image 161
polygenelubricants Avatar answered Sep 25 '22 08:09

polygenelubricants


Use m.toString() or String.valueOf(m). String.valueOf uses toString() but is null safe.

like image 21
krock Avatar answered Sep 26 '22 08:09

krock