Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 to Binary Conversion using Java

I already went over the responses I found for the question I have posted, but I wasn't able to figure out something. I would really appreciate it if somebody could please articulate on this a little bit:

I was trying to convert a base64 string into binary. I came across the following code, and I have the base64 string stored in a byte array. How can I convert the byte array into binary. The code I found:

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

import java.util.Arrays;

public class Base64Decode {
    public static void main(String[] args) {
           String hello = "AAADccwwCBwOAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAB==";

           byte[] decoded = Base64.decodeBase64(hello.getBytes());

           System.out.println(Arrays.toString(decoded));

          }
}

Output:

[0, 0, 3, 113, -52, 48, 8, 28, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Is the output correct? When I looked up some documentation for base64 conversion, I noticed the equivalent of "A" is 0. How does the array have a zero in the last slot? Would it not be having the equivalent of "B". Should my array not begin with three 0s then? How can I convert this into binary (in terms of 0s' and 1s')?

like image 978
Java_Coder Avatar asked May 01 '26 14:05

Java_Coder


1 Answers

In base 64, each character represents 6 bits of information. A four-character sequence represents 24 bits of information (i.e 3 bytes).

Then, the sequence AAAD represents {0,0,3}.

   AAAD -> 000000 000000 000000 000011 -> 00000000 00000000 00000011

The last sequence AAB=, where the final = is a padding character, represents a 16-bit value (there are actually 18 bits, but the last two bits are ignored), equivalent to {0, 0}.

   AAB= -> 000000 000000 000001 -> 00000000 00000000 (ignored: 01)

Had the last sequence been AB==, it would have represented an 8-bit value, equivalent to {0}.

   AB== -> 000000 000001 -> 00000000 (ignored: 0001)
like image 145
Javier Avatar answered May 03 '26 03:05

Javier