I have a String that I want to decode to a binary object (BigInteger or its String) Say for instance I got the String
String str = "LTEwMTAwMTEwMTExMA==";
An now I want to decode it using the Base64.getDecoder() method, such as:
String result = new BigInteger(Base64.getDecoder().decode(str.getBytes("UTF-8"))).toString(2);
According to that, the value of result is
101101001100010011000000110001001100000011000000110001001100010011000000110001001100010011000100110000
which does not match with the result that I obtain using any online decoder:
-101001101110
Could you please help me? what am I doing wrong? Thank you very much!
CodePudding user response:
You have an issue with your String conversions - try this instead:
String result = new BigInteger(new String(Base64.getDecoder().decode(encoded.getBytes("UTF-8")))).toString();
By converting the byte array to String using a new String constructor you're getting a simple String representation which BigInteger constructor knows how to parse. The result will be the expected -101001101110
CodePudding user response:
Base64.Decoder.decode()
produces a byte array, not a string, so you need to convert it. Then you can use the BigInteger
constructor that accepts a radix to specify base 2:
import java.io.IOException;
import java.math.BigInteger;
import java.util.Base64;
public class Test
{
public static void main(String args[]) throws IOException
{
String str = "LTEwMTAwMTEwMTExMA==";
String str2 = new String(Base64.getDecoder().decode(str), "UTF-8");
BigInteger big = new BigInteger(str2, 2);
System.out.println(big.toString(2));
}
}
Output:
-101001101110