3

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')?

1

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Javier, Thanks for the explanation. This helps! How do I convert the byte output into binary in Java?
If you want a string representation of the byte values, do new BigInteger(1, decoded).toString(2)
Thanks Javier!! I looked up the documentation for the BigInteger and understood the line of code. That answer was very helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.