Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert BigInteger to Shorter String in Java

I'm looking for a way to convert a BigInteger into a very short String (shortest possible). The conversion needs to be reversible. The security of the conversion is not a big deal in this case. Would anyone have recommendations or samples of how they would go about solving this problem?

like image 634
Dave Maple Avatar asked Apr 19 '11 13:04

Dave Maple


1 Answers

You can use a Base64 encoding. Note that this example uses Apache commons-codec:

BigInteger number = new BigInteger("4143222334431546643677890898767548679452");
System.out.println(number);

String encoded = new String(Base64.encodeBase64(number.toByteArray()));
System.out.println(encoded);

BigInteger decoded = new BigInteger(Base64.decodeBase64(encoded));
System.out.println(decoded);

prints:

4143222334431546643677890898767548679452
DC0DmJRYaAn2AVdEZMvmhRw=
4143222334431546643677890898767548679452
like image 69
Christoph Walesch Avatar answered Sep 29 '22 20:09

Christoph Walesch