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?
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.
The java. math. BigInteger. intValue() converts this BigInteger to an integer value.
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.
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.
Use m.toString()
or String.valueOf(m)
. String.valueOf uses toString() but is null safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With