Convert BigInteger to Shorter String in Java
Asked Answered
B

2

7

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?

Barde answered 19/4, 2011 at 13:8 Comment(2)
"hashing" and "reversible" doesn't match. A hash isn't reversible by design! What you're looking for is probably compression.Diode
Thanks Joachin. I've updated the question to be more clear.Barde
P
9

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

Pathological answered 19/4, 2011 at 13:18 Comment(2)
Neat, I didn't know about the Character.MAX_RADIX.Auspicious
MAX_RADIX is 36: from 0-9a-z. But you can use also uppercase chars using Base64 or Base62 if you want to have only alphanumeric characters, this class does the trick: github.com/opencoinage/opencoinage/blob/master/src/java/org/…Dipterous
S
9

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
Schaffer answered 19/4, 2011 at 13:34 Comment(1)
the "=" (or "==") at the end can be stripped out, as it is just padding, and the decoding works fine.Dipterous

© 2022 - 2024 — McMap. All rights reserved.