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,
First of all, I don’t believe PHP gives you above mentioned string (
000000000000000000000000000000000100000000000000) as an output!The code in your question enumerate each character in input string (
AAAAAEAA), retrieves ASCII value of each character and post it in output. If you execute PHP code you mentioned, you will give exact the same output, as running JAVA code you mentioned (0100000101000001010000010100000101000001010001010100000101000001).For example,
65 in turn has
01000001binary representation.Second, correct your question to get correct answer. It seems, guys, answered earlier, didn’t understand your question at all.
Third, if you want to get binary represenation of a given string, use getBytes() method to retrieve bytes representation of entire string. Use or adapt this code snippet to get binary representation of a given bytes-array.