Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Base64 encode binary String to binary in java?

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,

like image 994
Vansi Avatar asked May 07 '26 01:05

Vansi


1 Answers

To decode base64, the simplest is to use the Apache commons Decoder.

import org.apache.commons.codec.binary.Base64;

byte[] decodedBytes = Base64.decodeBase64(input);

Do you really need the binary as a string made of "0" and "1" chars ?

like image 125
Denys Séguret Avatar answered May 08 '26 16:05

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!