How do I decode a string from base 32 to a BigInteger
-
18-06-2021 - |
Question
I tried the following code:
import java.math.BigInteger;
import org.apache.commons.codec.binary.Base32;
import org.junit.Test;
public class Sandbox
{
@Test
public void testSomething() {
String sInput = "GIYTINZUHAZTMNBX";
BigInteger bb = new BigInteger(new Base32().decode(sInput));
System.out.println("number = " + bb);
}
}
and heres the output:
number = 237025977136523702055991
using this website to convert between base 32 I get a different result than the actual output. Heres the result I expect to see based on what I got from the website:
expected output = 2147483647
Any idea why this is happening?
Edit:
Forgive me for making it confusing by purposefully attempting to convert 2^31-1.
Using the conversion website I linked to earlier, I changed the input:
String sInput = "GE4DE===";
Expected output:
number = 182
Actual output:
number = 3225650
Solution
What you're doing is correct... assuming that the Base32 string comes from Base32-encoding a byte array you get from calling BigInteger.toByteArray()
.
BigInteger(byte[] val)
does not really take an array of arbitrary bytes. It takes the byte[]
representation of a BigInteger
. Also, it assumes the most-significant byte is in val[0]
).
OTHER TIPS
If it's base-32 the X, Y, and Z shouldn't be there. Are you sure it isn't base-36?