Skip to content
Advertisement

Base 64 decode to String not as expected

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!

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement