Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
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 (32.1k points)
edited by

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);

Become a certified Salesforce professional by taking up Intellipaat’s Salesforce Certification!
 

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...