Convert BigInteger to Shorter String in Java

北城余情 提交于 2019-12-19 08:23:07

问题


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?


回答1:


One easy way is to use BigInteger.toString(Character.MAX_RADIX). To reverse, use the following constructor: BigInteger(String val, int radix).




回答2:


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


来源:https://stackoverflow.com/questions/5716830/convert-biginteger-to-shorter-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!