views:

262

answers:

5

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() method but not getting desired result. why??? what is bug in it and what is its remedy.

+1  A: 

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

krock
i tried both.If my message is hello then in both ways i get their BigInteger value 448378203247 .but i want hello back not the integer
Bipul
If the BigInteger does represent a String then there does not seem to be any value in converting it into a byte[] or BigInteger. Why do you need to do that?
krock
+3  A: 

Why don't you use the BigInteger(String) constructor ? That way, round-tripping via toString() should work fine.

(note also that your conversion to bytes doesn't explicitly specify a character-encoding and is platform-dependent - that could be source of grief further down the line)

Brian Agnew
if i m using like BigInteger(String) constructor i m getting the exception:java.lang.NumberFormatException
Bipul
A: 

http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html

every object has a toString() method in Java.

Nils
i used toString() method but instead of printing msg in text it is printing its BigInteger value.
Bipul
+1  A: 

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.

polygenelubricants
u r right.a lot of thanx
Bipul
A: 

To reverse

byte[] bytemsg=msg.getBytes(); 

you can use

String text = new String(bytemsg); 

using a BigInteger just complicates things, in fact it not clear why you want a byte[]. What are planing to do with the BigInteger or byte[]? What is the point?

Peter Lawrey