hawx
hawx

Reputation: 1669

Convert Base64 to Binary String in Java

I have the following 3 byte encoded Base64 string.

    String base64_str = "MDQw";
    System.out.println("base64:" + base64_str);
    String hex = DatatypeConverter.printHexBinary(DatatypeConverter.parseBase64Binary(base64_str));

    for (int i = 0; i < hex.length(); i+=6) {
        String bytes = hex.substring(i, i+6);

        System.out.println("hex: " + bytes);

        StringBuilder binary = new StringBuilder();

        int byte3_int = Integer.parseInt(bytes.substring(4, 6), 16);
        String byte3_str = Integer.toBinaryString(byte3_int);
        byte3_int = Integer.valueOf(byte3_str);
        binary.append(String.format("%08d", byte3_int));

        int byte2_int = Integer.parseInt(bytes.substring(2, 4), 16);
        String byte2_str = Integer.toBinaryString(byte2_int);
        byte2_int = Integer.valueOf(byte2_str);
        binary.append(String.format("%08d", byte2_int));

        int byte1_int = Integer.parseInt(bytes.substring(0, 2), 16);
        String byte1_str = Integer.toBinaryString(byte1_int);
        byte1_int = Integer.valueOf(byte1_str);
        binary.append(String.format("%08d", byte1_int));

        System.out.println("binary: " + binary);
    }
}

My Output is:

base64:MDQw
hex: 303430
binary: 001100000011010000110000

The above output is correct, but is there a more efficient way on converting a base64 string to binary string?

Thanks in advance.

Upvotes: 0

Views: 16246

Answers (2)

yean
yean

Reputation: 1315

You can use BigInteger (import java.math.BigInteger;) to convert a base64 string to binary string.

byte[] decode = Base64.getDecoder().decode(base64_str);
String binaryStr = new BigInteger(1, decode).toString(2);

Upvotes: 4

Manticore
Manticore

Reputation: 480

Here is a small code to perform your operation. The only flaw is the use of replace for padding the 0.

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;

public class main {

    public static void main(String [] args) throws UnsupportedEncodingException {
        String base64_str = "MDQw";
        byte[] decode = DatatypeConverter.parseBase64Binary(base64_str);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < decode.length; i++){
            String temp = Integer.toBinaryString(decode[i]);
            sb.append(String.format("%8s", temp).replace(" ", "0"));
        }

        System.out.println(sb.toString());
    }
}

Upvotes: 2

Related Questions