简体   繁体   English

在 Java 中将 Base64 转换为二进制字符串

[英]Convert Base64 to Binary String in Java

I have the following 3 byte encoded Base64 string.我有以下 3 字节编码的 Base64 字符串。

    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?上面的输出是正确的,但是有没有更有效的方法将 base64 字符串转换为二进制字符串?

Thanks in advance.提前致谢。

You can use BigInteger (import java.math.BigInteger;) to convert a base64 string to binary string.您可以使用BigInteger (import java.math.BigInteger;) 将 base64 字符串转换为二进制字符串。

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

Here is a small code to perform your operation.这是一个小代码来执行您的操作。 The only flaw is the use of replace for padding the 0.唯一的缺陷是使用替换来填充 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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM