+1 vote
1 view
in Salesforce by (11.9k 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 (30.1k 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);

Related questions

0 votes
0 answers
asked Nov 19, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 17, 2019 in Java by adam96 (800 points)
0 votes
1 answer
asked Sep 26, 2019 in Java by Shubham (3.9k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...