Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to BigInteger representation and back in Java?

Let's suppose I have a String, let's call it foo. This String can contain any value, like letters, numbers, special characters, UTF-8 special characters, such as á and so on. For instance, this might be a real value:

"Érdekes szöveget írtam a tegnap, 84 ember olvasta."

I would like to have the following two methods:

public BigInteger toBigInteger(String foo)
{
    //Returns a BigInteger value that can be associated with foo
}

public String fromBigInteger(BigInteger bar)
{
    //Returns a String value that can be associated with bar
}

Then:

String foo = "Érdekes szöveget írtam a tegnap, 84 ember olvasta.";
System.out.println(fromBigInteger(toBigInteger(foo)));
//Output should be: "Érdekes szöveget írtam a tegnap, 84 ember olvasta."

How can I achieve this? Thanks

like image 701
Lajos Arpad Avatar asked Dec 07 '22 06:12

Lajos Arpad


1 Answers

The following code will do what you expect:

public BigInteger toBigInteger(String foo)
{
    return new BigInteger(foo.getBytes());
}

public String fromBigInteger(BigInteger bar)
{
    return new String(bar.toByteArray());
}

However I don't understand why you would need to do this and I would be interested of your explanation.

like image 184
LaurentG Avatar answered Jan 31 '23 00:01

LaurentG