+1 vote
1 view
in Salesforce by (11.3k points)

How can i convert the following Base64 encode binary string into a binary in java. I have seen people doing the same in php using the following code. How to achieve this in java?

In PHP:

$byteArr = "AAAAAEAA";

$maparray = array();

$map = "";

foreach(str_split($byteArr) as $c)

    $maparray [] = sprintf("%08b", ord($c));

$map = implode("", $maparray );

Output is $map -> "000000000000000000000000000000000100000000000000";

But when i try this in java:

String input = "AAAAAEAA";

String mapArray = "";

for(int b=0;b<input.length();b++){

   int asciValueOfChar =(int)toByte.charAt(b);

   String binaryInt = Integer.toBinaryString(asciValueOfChar);

   String paddedBinaryInt = String.format("%8s", binaryInt);

   paddedBinaryInt = paddedBinaryInt.replace(' ', '0');

   System.out.println("ASCII Code::"+asciValueOfChar);

   System.out.println("Binary of Char::"+binaryInt);

   System.out.println("Binary of Padded Char::"+binaryInt);

   mapArray = mapArray + paddedBinaryInt ;

}

System.out.println("Binary Array::"+mapArray);

Output is mapArray -> "0100000101000001010000010100000101000001010001010100000101000001"

The output varies.

How can I achieve the same output?

Thanks,

1 Answer

+1 vote
by (28.6k points)

You can use BigInteger (import java.math.BigInteger;) 

to convert a base64 string to binary string.

byte[ ] decode = Base64.decodeBase64(base64_str);

String binaryStr = new BigInteger(1, decode).toString(2);

...