How to convert String to and from BigInteger view in Java?

Suppose I have a String , call it foo . This String can contain any value, such as letters, numbers, special characters, UTF-8 special characters, such as á, etc. For example, this could 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

+4
source share
2 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 do not understand why you need this, and I would be interested to know your explanation.

+10
source

Ignoring "Why Do You Do This?"

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

and then

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

Edit Comment:. The default encoding is used. If the String source is not encoded by default, you must specify the appropriate Charset for both getBytes() and the constructor for String . And if by chance you use an encoding in which the first byte is zero, this will fail.

+4
source

Source: https://habr.com/ru/post/1489572/


All Articles