简体   繁体   中英

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

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.

Ignoring the "Why would you ever want to do that?"

String foo = "some text";
byte[] fooBytes = foo.getBytes();
BigInteger bi = new BigInteger(fooBytes);

and then

foo = new String(bi.toByteArray());

Edit from comments: This is using the default charset. If the source String is not encoded via your default, you would want to specify the appropriate Charset to both getBytes() and the constructor for String . And if by chance you're using a charset that the first byte is zero, this will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM